简体   繁体   English

jQuery 1.6 未在复选框更改时将 class 添加到元素

[英]jQuery 1.6 not adding class to element on checkbox change

This code works fine with jQuery 1.5.1, but when I use jQuery 1.6.0 it changes the value of the checkbox after click, but it does not add the class 'done' to the element.此代码适用于 jQuery 1.5.1,但当我使用 jQuery 1.6.0 时,它会在单击后更改复选框的值,但不会将 class'添加到元素'。

$("input:checkbox").live('change', function(eve) {
    eve.preventDefault();
    var el =  this.id ;
    var done =  this.done ;
    if( $(this).attr("checked") == true ) {
        $('#item-'+el).find(".text").addClass('done');
        //return false;
    }
    if( $(this).attr("checked") == false ) {
        $('#item-'+el).find(".text").removeClass('done');
        //return false;
    }

    $.post('taskDone.php', {
        id: this.id,
        value: $(this).attr("checked") ? 1 : 0
    }, function(data) {});
});

prior to 1.6 1.6 之前

$(this).attr("checked") is inconsistent, as it can be a boolean or it can be a string $(this).attr("checked")不一致,因为它可以是boolean也可以是字符串

jQuery says something like: attribute is what's inside a property. jQuery 表示类似:属性是属性内部的内容。 so, it stopped sending you a bool value and it's sending you a string value instead.因此,它停止向您发送bool值,而是向您发送string值。

if you change all如果你改变所有

$(this).attr("checked")

to

$(this).prop("checked")

you will have no problems你不会有任何问题


from jQuery Documentation来自jQuery 文档

For example, consider a DOM element defined by the HTML markup <input type="checkbox" checked="checked" /> , and assume it is in a JavaScript variable named elem:例如,考虑由 HTML 标记<input type="checkbox" checked="checked" />定义的 DOM 元素,并假设它位于名为 elem 的 JavaScript 变量中:

elem.checked                       true (Boolean)
$(elem).prop("checked")            true (Boolean)
elem.getAttribute("checked")       "checked" (String)
$(elem).attr("checked")(1.6+)      "checked" (String)
$(elem).attr("checked")(pre-1.6)   true (Boolean)

Or update to version 1.6.1.或者更新到 1.6.1 版本。 The attr() function will behave as in 1.5, so you don't have to crawl through your code to find every call to attr() and decide if you need to change it to prop(). attr() function 的行为与 1.5 中一样,因此您不必遍历代码来查找对 attr() 的每个调用并决定是否需要将其更改为 prop()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM