【问题标题】:jQuery: Check / uncheck all siblings with certain classjQuery:选中/取消选中某个类的所有兄弟姐妹
【发布时间】:2015-05-28 12:17:42
【问题描述】:

我是 jQuery 新手,希望这里有人可以帮助我解决这个问题。

我正在尝试设置一个“全部”复选框来选中/取消选中其所有同级复选框(即那些在同一个 div/父级下的复选框) - 但前提是它们没有特定的类("other")。

我的方法是使运行时间最少,并以一种也可以应用于其他 div 中的类似结构的方式编写它。

我的代码在没有:not() 选择器的情况下工作,但是当我包含它时我无法让它工作。 另外,我不确定我的方法是否是这里最好/最快的方法。

我的 jQuery:

$('.checkAll').click(function(){
    if($(this).is(':checked')){
        $(this).siblings(":not($('.other'))").prop('checked', true);
    }else{
        $(this).siblings(":not($('.other'))").prop('checked', false);
    }
});

非常感谢您的任何帮助, 迈克

【问题讨论】:

  • 来自 w3.org: Note: During the handling of a click event on an input element with a type attribute that has the value "radio" or "checkbox", some implementations may change the value of this property before the event is being dispatched in the document. 所以你应该使用 change 事件而不是所有现代浏览器都很好地支持 click 事件 AFAIK。编辑:刚刚检查了 jQuery 源代码,并且像往常一样,这是考虑到(标准化),请参见下面的代码:
  • /* For checkbox, fire native event so checked state will be right */ trigger: function() { if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) { this.click(); return false; } },
  • @A.Wolff:也谢谢你!

标签: jquery checkbox jquery-selectors checked siblings


【解决方案1】:

jQuery Selector 内不需要 :not

$('.checkAll').on('click', function() {
    $(this).siblings(":not('.other')").prop('checked', $(this).is(':checked'));
});

$(this).is(':checked') 返回您使用 if 检查过的 true/false,并将其分配给 checked

【讨论】:

  • 感谢您的快速回复 - 这很有帮助!我会尽快接受。 :)
  • 只是为了以后做这件事,你能解释一下你代码的最后一部分吗?这只是编写 if 语句的一种简短方式吗?
  • @keewee279 添加。检查答案
【解决方案2】:

:not 中不需要$。您可以使用 this.checked 优化您的代码并避免使用 if 语句。

$('.checkAll').click(function(){
      $(this).siblings(":not('.other')").prop('checked', this.checked);
});

【讨论】:

  • 也谢谢你!
【解决方案3】:

删除非选择器中的jquery对象,可以使用字符串

 $(this).siblings(":not('.other')").prop('checked', true);

【讨论】:

    猜你喜欢
    • 2012-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-07
    • 1970-01-01
    • 1970-01-01
    • 2011-01-09
    • 2015-03-05
    相关资源
    最近更新 更多