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

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

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

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


当前回答

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

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

其他回答

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

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

这就是要找出复选框是否被选中的解决方案。 使用#prop()函数//

$("#c_checkbox").on('change', function () {
                    if ($(this).prop('checked')) {
                        // do stuff//
                    }
                });

只是另一种解决方案

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

尝试这种“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 > ...