使用prop()检查复选框不会触发附加到"更改"的事件

125*_*748 25 html javascript jquery

使用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>
Run Code Online (Sandbox Code Playgroud)

JS

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

  alert("checked");

});


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

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

});
Run Code Online (Sandbox Code Playgroud)

单击复选框时会触发警报.当复选框的属性发生变化时,如何触发它?JSBIN

Ser*_*gio 30

您必须使用.change()来触发更改事件侦听器:

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


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

JSBbin或小提琴

请注意,这将引发许多事件.在jsBin中的html示例中有三个.


小智 7

从函数内部触发事件:

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

  • 我发现使用`.trigger("change")`更优雅,因为它可以在设置检查后直接执行. (3认同)