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

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

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

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


当前回答

很简单,这是我使用的方法:

JQuery:

$(document).on('change', '[name="nameOfCheckboxes[]"]', function() {
    var checkbox = $(this), // Selected or current checkbox
        value = checkbox.val(); // Value of checkbox

    if (checkbox.is(':checked'))
    {
        console.log('checked');
    }else
    {
        console.log('not checked');
    }
});

的问候!

其他回答

试试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>

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

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

基于事件(点击事件)采取的动作。

$('#my_checkbox').on('click',function(){
   $('#my_div').hide();
   if(this.checked){
     $('#my_div').show();
   }
});

没有事件根据当前状态采取行动。

$('#my_div').hide();
if($('#my_checkbox').is(':checked')){
  $('#my_div').show();
}

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

// $(<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>

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

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

    })
})

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

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

    })
})

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

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