当一个复选框被选中/取消选中时,我想要一个事件来触发客户端:

$('.checkbox').click(function() {
  if ($(this).is(':checked')) {
    // Do stuff
  }
});

基本上,我希望它发生在页面上的每个复选框上。这种点击并检查状态的方法是否正确?

我在想一定有一个更干净的jQuery方式。有人知道解决办法吗?


当前回答

尝试这种“html方法”,它适用于小型JS项目

函数msg(animal,is) { console.log(动物,is.checked);//做事情 } <input type="checkbox" oninput="msg('dog', this)"你养狗吗?< br > <input type="checkbox" oninput="msg('frog',this)"你有一只青蛙吗?< br > ...

其他回答

试试jQuery验证

$(document).ready(function() { $('#myform').validate({ // initialize the plugin rules: { agree: { required: true } }, submitHandler: function(form) { alert('valid form submitted'); return false; } }); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.js"></script> <form id="myform" action="" method="post"> <div class="buttons"> <div class="pull-right"> <input type="checkbox" name="agree" /><br/> <label>I have read and agree to the <a href="https://stackexchange.com/legal/terms-of-service">Terms of services</a> </label> </div> </div> <button type="submit">Agree</button> </form>

绑定到更改事件,而不是单击。然而,你可能仍然需要检查复选框是否被选中:

$(".checkbox").change(function() {
    if(this.checked) {
        //Do stuff
    }
});

与单击事件相比,绑定到更改事件的主要好处是,并不是所有对复选框的单击都会导致它改变状态。如果您只想捕获导致复选框更改状态的事件,则需要名称恰当的更改事件。在评论中编辑

还要注意,我使用了这个。而不是将元素包装在jQuery对象中并使用jQuery方法,因为直接访问DOM元素的属性更短、更快。

编辑(见评论)

要获得所有复选框,您有两个选项。你可以使用:复选框伪选择器:

$(":checkbox")

或者你可以使用属性=选择器:

$("input[type='checkbox']")

如果您的意图是仅在选中的复选框上附加事件(因此当它们未选中并稍后再次选中时,它将触发),那么这就是您想要的。

$(function() {
    $("input[type='checkbox']:checked").change(function() {

    })
})

如果您打算将事件附加到所有复选框(已选中和未选中)

$(function() {
    $("input[type='checkbox']").change(function() {

    })
})

如果你想让它只在被检查(从未检查)时发射,那么@James Allardice回答上面的问题。

BTW input[type='checkbox']:checked是CSS选择器。

它还可以通过以下方式实现。当复选框被触发时,div 或带有#checkbox id的控件被隐藏或以其他方式显示。

 <script>
      $('#checkbox').on('click',function(){
          if(this.checked){
              $('#checkbox').hide();
           }else{
              $('#checkbox').show();
           }
      });
 </script>

如果您动态添加复选框,上面正确的可接受答案将不起作用,以供将来在这里遇到困难的人参考。您将需要利用事件委托,它允许父节点从特定的后代捕获冒泡事件并发出回调。

// $(<parent>).on('<event>', '<child>', callback);
$(document).on('change', '.checkbox', function() {
    if(this.checked) {
      // checkbox is checked
    }
});

注意,对于父选择器,几乎总是没有必要使用document。相反,选择一个更特定的父节点,以防止将事件传播到太多的级别。

下面的示例显示动态添加的dom节点的事件如何不触发先前定义的侦听器。

$postList = $('#post-list'); $postList.find('h1').on('click', onH1Clicked); function onH1Clicked() { alert($(this).text()); } // simulate added content var title = 2; function generateRandomArticle(title) { $postList.append('<article class="post"><h1>Title ' + title + '</h1></article>'); } setTimeout(generateRandomArticle.bind(null, ++title), 1000); setTimeout(generateRandomArticle.bind(null, ++title), 5000); setTimeout(generateRandomArticle.bind(null, ++title), 10000); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <section id="post-list" class="list post-list"> <article class="post"> <h1>Title 1</h1> </article> <article class="post"> <h1>Title 2</h1> </article> </section>

此示例显示了事件委托的用法,以捕获特定节点(本例中为h1)的事件,并为此类事件发出回调。

$postList = $('#post-list'); $postList.on('click', 'h1', onH1Clicked); function onH1Clicked() { alert($(this).text()); } // simulate added content var title = 2; function generateRandomArticle(title) { $postList.append('<article class="post"><h1>Title ' + title + '</h1></article>'); } setTimeout(generateRandomArticle.bind(null, ++title), 1000); setTimeout(generateRandomArticle.bind(null, ++title), 5000); setTimeout(generateRandomArticle.bind(null, ++title), 10000); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <section id="post-list" class="list post-list"> <article class="post"> <h1>Title 1</h1> </article> <article class="post"> <h1>Title 2</h1> </article> </section>