木子屋 Dnawo's BLOG

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

👤 dnawo 📅 2013-09-11 👁 4154 👍 0 💬 0 🔄 本站原创
早前一直用下边方法判断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)

暂无评论。

计算题
评论需审核通过后显示
← 上一篇 EasyUI表单项获取和设置值示例 下一篇 → ASP.NET MVC3视图占位符RenderSection使用…