【问题标题】:jQuery addClass to every item that have x children?jQuery addClass 到每个有 x 孩子的项目?
【发布时间】:2011-10-03 16:43:58
【问题描述】:

我想为每个有 2 个以上孩子的项目添加“任何东西”类。 不幸的是我的代码不起作用,我想我必须定义 (this) 并且可能使用每个,但我不知道该怎么做。

这是我的代码:

if ( jQuery('#container .document').children().size() > 2 ) {
     jQuery(this).addClass("anything"); 
}

一个破例:

http://jsfiddle.net/HHSuM/1/

【问题讨论】:

  • 一些小事:(1)$( '.document', '#container' ) 效率更高。 (2) 如果您的 jQuery 代码在 ready 处理程序中(无论如何都应该在其中),您不必使用 jQuery 而不是 $,因为您可以将 $ 名称传递给此处理程序:@ 987654327@

标签: jquery size each children addclass


【解决方案1】:

您可以使用filter 将列表限制为具有两个以上子级的元素。

jQuery('#container .document').filter(function() {
    return this.children.length > 2; //Use just the regular DOM children property in here
}).addClass("anything");

JSFiddle:http://jsfiddle.net/HHSuM/4/

【讨论】:

  • 感谢childElementCount 的提醒。 :)
【解决方案2】:

使用.each()循环遍历元素:

$('#container .document').each(function() {
  if (this.children.length > 2) {
    $(this).addClass('anything');
  }
});

【讨论】:

  • 你也可以测试($(this).children(:gt(1)).length),但我怀疑使用>而不是:gt会更快。
  • 谢谢,我还有一个问题,如果我的页面上有大约 50 个 .document 元素并且它们有大约 50-100 个孩子 - 这段代码会大大降低我的网站速度吗?
  • 不。您只需遍历 50 个.documents 并计算孩子的数量,这不会超过几分之一秒。你试过运行代码了吗?
  • @Blender 应该是children()(带括号)。 $(this).children().lengththis.children.length
  • @Blender,是的,它就像一个魅力,至少在本地主机上。十分感谢! :)
【解决方案3】:

我认为这是一个有趣的问题,并尝试将 :has():nth-child() 结合使用,但出现语法错误。

// Does NOT work... why?
jQuery('#container .document:has(*:nth-child(3))').addClass('anything');

但是稍微修改一下方法,就可以了:

// Nifty!
jQuery('#container .document *:nth-child(3)').parents('.document').addClass('anything');

基本上我们正在寻找具有第三个元素的元素,然后向上移动 DOM。

【讨论】:

  • 必须给你,它确实是一个漂亮的选择器,虽然为了简单起见,我仍然会使用.filter(),不过确实是一个很棒的发现
【解决方案4】:

使用.each() 遍历#container .document 元素。

更新了您的jsfiddle。似乎有效!

【讨论】:

    【解决方案5】:

    这里有很多选择

    1. 您可以使用 .each() 遍历项目,在回调函数中检查它们是否有 2 个或更多孩子,然后添加类

    2. 我更喜欢的另一个选项是像这样使用 .filter():

      $('#container .document').filter(function(){  
          return $(this).children().length > 2;
      }).addClass('anything');
      

      或者你的例子:http://jsfiddle.net/saelfaer/HHSuM/6/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-16
      • 1970-01-01
      • 2012-09-20
      • 2016-07-08
      • 2023-04-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多