使用 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();
});
JSBbin或 Fiddle
请注意,这会触发许多事件。 jsBin 中的 html 示例中的三个。
关于javascript - 使用 prop() 选中的复选框不会触发附加到 "change"的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19505011/