3

我正在使用 jQuery 手风琴,每个手风琴容器都有一组复选框。在每一个中,我有 2 个按钮(选择和取消选择),点击时,我希望它们只选择/取消选择该特定手风琴容器中的所有复选框。这非常令人沮丧,因为我确信代码是正确的,所以希望有人能发现我的愚蠢并帮助兄弟:

jQuery:

 // Select all for groups:
   $(".group_buttons").on("click",function() {
       var btn_request = $(this).attr("rel");
       var group = $(this);
       if(btn_request == "add") {
           $(this).parent(".controller_box").find('input:checkbox')
                .attr('checked',true);
       } else {
           $(this).parent(".controller_box").find('input:checkbox')
                .attr('checked', false);
       }
       return false;
   });

示例 HTML:

  <div class='controller_box'>
       <a href='' rel='add' class='group_buttons'>Select all</a>
       <a href='' rel='rem' class='group_buttons'>Select all</a>
       <input type='checkbox' name='sample1' value=1 />
       <input type='checkbox' name='sample2' value=1 />
  </div>
4

1 回答 1

3

你可以使用prop()方法:

属性和属性之间的区别在特定情况下可能很重要。在 jQuery 1.6 之前,.attr() 方法在检索某些属性时有时会考虑属性值,这可能会导致行为不一致。从 jQuery 1.6 开始,.prop() 方法提供了一种显式检索属性值的方法,而 .attr() 检索属性。

$(".group_buttons").on("click",function() {
   var btn_request = $(this).attr("rel");
   if(btn_request == "add") {
       $(this).parent().find('input[type="checkbox"]').prop('checked', true);
   } else {
       $(this).parent().find('input[type="checkbox"]').prop('checked', false);
   }
   return false;
});

请注意:checkbox选择器是deprecated.


如果.group_buttons是动态生成的,您应该委托click事件:

$("body").on('click', '.group_buttons', function() {
   var btn_request = $(this).attr("rel");
   if(btn_request == "add") {
       $(this).parent().find('input[type="checkbox"]').prop('checked', true);
   } else {
       $(this).parent().find('input[type="checkbox"]').prop('checked', false);
   }
   return false;
});
于 2012-07-21T11:28:53.913 回答