如何在Jquery中选中复选框时进行监听 [英] How to listen to when a checkbox is checked in Jquery

查看:126
本文介绍了如何在Jquery中选中复选框时进行监听的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要知道何时选中页面上的任何复选框:

I need to know when any checkbox on the page is checked:

例如

<input type="checkbox">

我在Jquery中尝试过

I tried this in Jquery

$('input type=["checkbox"]').change(function(){
alert('changed');
});

但这没用,有什么主意吗?

But it didn't work, any ideas?

推荐答案

使用change()事件和is()测试:

$('input:checkbox').change(
    function(){
        if ($(this).is(':checked')) {
            alert('checked');
        }
    });

我将以上内容更新为以下内容,因为我愚蠢地依赖jQuery(在if中),而DOM属性同样合适,并且使用起来也更便宜.为了使选择器能够在支持它的那些浏览器中传递给DOM的document.querySelectorAll()方法,

I've updated the above, to the following, because of my silly reliance on jQuery (in the if) when the DOM properties would be equally appropriate, and also cheaper to use. Also the selector has been changed, in order to allow it to be passed, in those browsers that support it, to the DOM's document.querySelectorAll() method:

$('input[type=checkbox]').change(
    function(){
        if (this.checked) {
            alert('checked');
        }
    });

为了完整起见,在普通的JavaScript中也可以很容易地实现相同的事情:

For the sake of completion, the same thing is also easily possible in plain JavaScript:

var checkboxes = document.querySelectorAll('input[type=checkbox]'),
    checkboxArray = Array.from( checkboxes );

function confirmCheck() {
  if (this.checked) {
    alert('checked');
  }
}

checkboxArray.forEach(function(checkbox) {
  checkbox.addEventListener('change', confirmCheck);
});


参考文献:


References:

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆