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

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

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

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


当前回答

关键是:使用prop而不是attr来查询已检查的状态,例如:

jQuery('#my_check_tag').prop('checked') //返回正确的状态 jQuery('#my_check_tag').attr('checked') //总是返回undefined

其他回答

只是另一种解决方案

$('.checkbox_class').on('change', function(){ // on change of state
   if(this.checked) // if changed state is "CHECKED"
    {
        // do the magic here
    }
})

也许这是你的另一种选择。

<input name="chkproperty" onchange="($(this).prop('checked') ? $(this).val(true) : $(this).val(false))" type="checkbox" value="true" />`

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

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

    })
})

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

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

    })
})

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

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

$(document).ready(function () {
    $(document).on('change', 'input[Id="chkproperty"]', function (e) {
        alert($(this).val());
    });
});

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

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');
    }
});

的问候!