Undefined is not a function (jQuery add/remove cla

2020-04-23 06:50发布

I'm making a simple swap button which doesn't seem to work.

HTML

<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
</head>

<body>
<a onclick="paid(123);" class="no" id="123"></a>
<a onclick="paid(124);" class="yes" id="124"></a>
<a onclick="paid(125);" class="no" id="125"></a>
</body>
</html>

JAVASCRIPT

<script type="text/javascript">
function paid(currentId) {

if (document.getElementById(currentId).hasClass("no")) {
    document.getElementById(currentId).removeClass( 'no' ); 
    document.getElementById(currentId).addClass( 'yes' );   
}

else if (document.getElementById(currentId).hasClass("yes")) {
    document.getElementById(currentId).removeClass( 'yes' );    
    document.getElementById(currentId).addClass( 'no' );    
}

}
</script>

Am I missing something obvious here? :)

3条回答
劳资没心,怎么记你
2楼-- · 2020-04-23 07:36

Instead of creating function paid(), you can use jQuery like this:

jQuery(document).ready(function(){
    jQuery('a').click(function(){
        jQuery(this).toggleClass('yes');
        jQuery(this).toggleClass('no');
    })
})

This will bind click event to Anchor tag and toggle Classes.

查看更多
Lonely孤独者°
3楼-- · 2020-04-23 07:41

You're not using jQuery to select those elements, so they don't have the hasClass, removeClass and addClass methods. They are just DOM elements. Use this instead:

function paid(currentId) {

// Select the element using jQuery
var $elem = $("#"+currentId);

if ($elem.hasClass("no")) {
    $elem.removeClass( 'no' ); 
    $elem.addClass( 'yes' );   
}

else if ($elem.hasClass("yes")) {
    $elem.removeClass( 'yes' );    
    $elem.addClass( 'no' );    
}

}

Additionally, you should not use onclick attributes. You should use the jQuery syntax instead:

$("a").on("click", function() {
    if ($(this).hasClass("no")) {
        $(this).removeClass( 'no' ); 
        $(this).addClass( 'yes' );   
    }

    else if ($(this).hasClass("yes")) {
        $(this).removeClass( 'yes' );    
        $(this).addClass( 'no' );    
    }
});

Finally, (trying to be nice here!) you should read a good jQuery tutorial as it seems you haven't fully grasped the techniques required to use the library.

查看更多
劳资没心,怎么记你
4楼-- · 2020-04-23 07:46

A pure javascript solution will be like this:

HTML

<a onclick="paid(this);" class="no" id="123">Link1</a>
<a onclick="paid(this);" class="yes" id="124">Link1</a>
<a onclick="paid(this);" class="no" id="125">Link1</a>

jQuery

function paid(current) {
   if(current.className == "no") {
      current.className = 'yes';
   } else if(current.className == "yes") {
      current.className = 'no';
   }
}

Fiddle

查看更多
登录 后发表回答