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

$('.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" />`

其他回答

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

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

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

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

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

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