未定义不是一个函数(jQuery add / remove类) [英] Undefined is not a function (jQuery add/remove class)

查看:331
本文介绍了未定义不是一个函数(jQuery add / remove类)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在建立一个似乎不起作用的简单交换按钮。

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? :)

推荐答案

你没有使用jQuery来选择这些元素,所以他们没有 hasClass removeClass addClass 方法。它们只是DOM元素。请改用:

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' );    
}

}

此外, code> onclick 属性。您应该使用jQuery语法:

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' );    
    }
});

最后,(试图在这里很好!)你应该阅读一个好的jQuery教程,因为它似乎你没有完全掌握使用该库所需的技术。

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.

这篇关于未定义不是一个函数(jQuery add / remove类)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆