Jquery点击事件只触发一次的解决方法

来源:互联网 发布:电大和网络教育的区别 编辑:程序博客网 时间:2024/05/16 13:38

方案一:

<script>$(function () { $("#all").click(function(){        if(this.checked){            $("#list :checkbox").attr("checked", true);       }else{            $("#list :checkbox").attr("checked", false);     }    });});</script>

方案二:

<script>$(function () { $("#all").click(function(){        if(this.checked){            $("#list :checkbox").prop("checked", true);       }else{            $("#list :checkbox").prop("checked", false);     }    });});</script>

今天在设置checkbox全选功能时,使用方案一在测试时发现全选功能在页面不刷新的情况下只能执行一次, 查看官方文档, 才知道从 jQuery 1.6 开始新增了一个方法 prop(),但是一直都没有使用过。

从中文意思看,两者分别是获取/设置 attributes 和 properties 的方法,那么为什么还要增加 prop() 方法呢?

Before jQuery 1.6, the .attr() method sometimes took property values
into account when retrieving some attributes, which could cause
inconsistent behavior.

因为在 jQuery 1.6 之前,使用 attr() 有时候会出现不一致的行为。

那么,什么时候使用attr(),什么时候使用prop()?

To retrieve and change DOM properties such as the checked, selected,
or disabled state of form elements, use the .prop() method.

根据官方的建议:具有 true 和 false 两个属性的属性,如 checked, selected 或者 disabled 使用prop(),其他的使用 attr()

到此,将 attr(‘checked’) 改成 prop(‘checked’) 即可修复提的 issues 了。

0 0