【问题标题】:Jquery checkbox prop method with change event带有更改事件的 Jquery 复选框道具方法
【发布时间】:2017-12-27 10:53:33
【问题描述】:

我需要对从另一个复选框选中的复选框执行一些操作。但它不起作用。为什么?简单例子:

$('.tmp').click(function(){
  $('.quest:not(:checked)').prop('checked', true);  
});

$('.quest').change(function(){
  console.log(this);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="" id="" class="tmp"> Click me to see some magic... or not(
<br>

<input type="checkbox" name="" id="" class="quest">1
<input type="checkbox" name="" id="" class="quest">2
<input type="checkbox" name="" id="" class="quest">3
<input type="checkbox" name="" id="" class="quest">4
<input type="checkbox" name="" id="" class="quest">5
<input type="checkbox" name="" id="" class="quest">6
<input type="checkbox" name="" id="" class="quest">7
<input type="checkbox" name="" id="" class="quest">8
<input type="checkbox" name="" id="" class="quest">9
<input type="checkbox" name="" id="" class="quest">10

【问题讨论】:

  • 这不会触发,因为您需要在 document.ready 函数中绑定该事件。

标签: jquery events checkbox prop


【解决方案1】:

您需要使用trigger方法手动触发change事件,例如:

$('.quest:not(:checked)')
.prop('checked', true) // updating prop but the change event is not fired
.trigger('change'); // this line will trigger the change event on .quest

【讨论】:

    【解决方案2】:

    您需要根据添加复选框属性检查是否选中了.tmp

    $('.tmp').click(function(){
        if($(this).is(':checked')){
            $('.quest').prop('checked', true);
        } else {
            $('.quest').prop('checked', false);
        }
    });
    

    【讨论】:

      【解决方案3】:
      $(document).ready(function () {
          $('.tmp').click(function () {
              $('.quest:not(:checked)').prop('checked', true);
          });
         $('.quest').change(function(){
         console.log(this);
         });
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-01-15
        • 2011-10-25
        • 1970-01-01
        • 2011-12-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多