jQuery不同版本判断checkbox是否选中方法比较

早前一直用下边方法判断checkbox是否选中:

if ($(elem).attr("checked") == true) {
    //...
}

但从jQuery1.6开始这个方法不好用,下边是jQuery两个版本获取checkbox的checked属性值比较:

jQuery1.5.2:


jQuery1.6.0:


官方文档中有如下说明:

引用内容 引用内容
As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method.

也就是说,从1.6开始,attr方法获取checkbox的checked属性值只有undefined和checked,所以,从1.6开始判断checkbox是否选中要用以下方法:

if ($(elem).attr("checked") == "checked") {
    //...
}

//or

if ($(elem).prop("checked") == true) {
    //...
}

其实,我们还有其他方法来判断checkbox是否选中,以下方法在jQuery各版本都适用,推荐使用:

if ($(elem).is(":checked")) {
    //...
}

参考资料

[1].attr方法:http://api.jquery.com/attr/
[2].jQuery1.5.2:http://code.jquery.com/jquery-1.5.2.min.js
[3].jQuery1.6.0:http://code.jquery.com/jquery-1.6.min.js

评论: 0 | 引用: 0 | 查看次数: 3473
发表评论
登录后再发表评论!