jQuery addClass 仅适用于具有更高级别的 div

Posted

技术标签:

【中文标题】jQuery addClass 仅适用于具有更高级别的 div【英文标题】:jQuery addClass only to div with class which is really higher 【发布时间】:2015-07-08 18:57:12 【问题描述】:

下面的代码导致具有此类的所有 div 都得到填充,包括这些不高于 200 的 div,但我只需要为确实大于 200 的元素添加填充。其余的必须保持没有填充。有谁知道我怎么能得到它?

var n = $('.class');
var height = n.height();
if (height > 200) 
   n.addClass('padding');

【问题讨论】:

【参考方案1】:

使用each() 函数迭代.class 元素并检查每个高度。

然后将.padding类应用于身高高于200px的人:

$('.class').each(function() 
  var that = $(this);
  if (that.height() > 200) 
     that.addClass('padding');
  
);

【讨论】:

【参考方案2】:

使用.filter 仅选择具有所需高度的元素:

$(".class").filter(function() 
    return $(this).height() > 200;
).addClass("padding");

在您的代码中,n.height() 仅返回所选第一个元素的高度,它不会更改 nn.addClass() 调用中所指的内容。

【讨论】:

以上是关于jQuery addClass 仅适用于具有更高级别的 div的主要内容,如果未能解决你的问题,请参考以下文章