javascript - 如果不是通过单击更改复选框,如何使用 jQuery 进行监听?

标签 javascript jquery html checkbox

我有许多使用另一个 jQuery 语句更改状态(已选中,未选中)的复选框:

元素:

<input type="checkbox" id="select_a">select group A</input>
<input type="checkbox" id="select_b">select group B</input>
<input type="checkbox" id="mix">select mix</input>

<div id="group_a">
    <input type="checkbox" id="a_1">group A_1</input>
    <input type="checkbox" id="a_2">group A_2</input>
</div>
<div id="group_b">
    <input type="checkbox" id="b_1">group B_1</input>
    <input type="checkbox" id="b_2">group B_2</input>
</div>

JQUERY

jQuery("#select_a").click(function () {
    if (this.checked) jQuery("div#group_a input:checkbox").prop("checked", true);
    else jQuery("div#group_a input:checkbox").prop("checked", false);
});
jQuery("#select_b").click(function () {
    if (this.checked) jQuery("div#group_b input:checkbox").prop("checked", true);
    else jQuery("div#group_b input:checkbox").prop("checked", false);
});
jQuery("#mix").click(function () {
    if (this.checked) {
        jQuery("#a_1").prop("checked", true);
        jQuery("#b_1").prop("checked", true);
    } else {
        jQuery("#a_1").prop("checked", false);
        jQuery("#b_1").prop("checked", false);
    }
});

我需要一种方法来为组中的每个复选框设置一个监听器,我使用这种方式工作如下:

jQuery("div input:checkbox").click(function(e){
    alert(e.target.id);
}); 

但这只有在鼠标单击复选框时才有效,我想要一种方法来为每个复选框触发一个事件(设置一个监听器),如果它被鼠标以外的其他东西选中的话。

Demo

最佳答案

您可以使用 change() 事件处理器

jQuery("div input:checkbox").change(function(){
     alert(this.id);
}); 

关于javascript - 如果不是通过单击更改复选框,如何使用 jQuery 进行监听?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31958488/

相关文章:

javascript - 如果焦点后输入字段为空,则重新填充输入字段值

javascript - 将倒计时设置为仅在周一和周三之间显示

php - 单击按钮/链接将数据保存到数据库

jquery - 在选择元素内使用键盘和鼠标输入创建 jQuery 事件触发器

html - 我不能让这个容器 css - html

javascript oninput 只触发一次?

javascript - 将图像保存到 Canvas 然后绘制更多

javascript - 根网址javascript

jquery - DataTables:从 JSON 生成整个表

javascript - 在悬停时显示和隐藏列表项