javascript - 使用 prop() 选中的复选框不会触发附加到 "change"的事件

标签 javascript jquery html

使用 jQuery prop() 检查的框不会影响附加到 change 处理程序的监听器。

我的代码是这样的

HTML

<div>
    <label>
        <input type="checkbox" class="ch" />test</label>
    <label>
        <input type="checkbox" class="ch" />test</label>
    <label>
        <input type="checkbox" class="ch" />test</label>
    <input type="button" value="check the box" id="select" />
</div>

JS

 $("body").on("change", ".ch", function(){

  alert("checked");

});


$("body").on("click", "#select", function(){

  $(this).parent("div").find("input[type=checkbox]").prop("checked", true);

});

当我点击复选框时会触发警报。当复选框的属性发生变化时,如何让它触发? JSBIN

最佳答案

你必须使用 .change()触发更改事件监听器:

$("body").on("change", ".ch", function () {
    alert("checked");
});


$("body").on("click", "#select", function () {
    $(this).parent("div").find("input[type=checkbox]").prop("checked", true).change();
});

JSBbinFiddle

请注意,这会触发许多事件。 jsBin 中的 html 示例中的三个。

关于javascript - 使用 prop() 选中的复选框不会触发附加到 "change"的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19505011/

相关文章:

javascript - 使用 iimPlay 时 iMacro/JS RuntimeError 933

jquery 月份选择器 : setting an initial min/max range conflicts with "from" <"to" function

javascript - 如何在没有输入提交的情况下提交表单

javascript - jquery中如何分割html标签?

javascript - React 和 Redux Reducer 没有改变

javascript - IE9、showModalDialog() 和 window.close() - 兼容性 View 的怪癖

javascript - 什么是被动事件监听器?

javascript - 如何将文本从 <a> 传递到另一个页面上的文本区域?

javascript - 如何在 div 的背景中加载谷歌地图?

javascript - 第二次单击时停止选项卡式元素关闭