jQuery:你可以选择CSS规则,而不是类吗?

.container可以包含许多.components,.components本身可以包含.containers(反过来可以包含.components等)。

给出这样的代码:

$(".container .component").each(function(){ $(".container", this).css('border', '1px solid #f00'); }); 

我需要添加到大括号内的行,以仅选择CSS中宽度设置为“auto”的嵌套.container? 我确信这很简单,但我还没有真正使用过jQuery。

 $(".container .component").each(function() { $(".container", this).each(function() { if($(this).css('width') == 'auto') { $(this).css('border', '1px solid #f00'); } }); }); 

与其他答案类似,但由于组件也可以有多个容器,因此也需要.each()检查宽度。

您可能想要查看.filter()

就像是:

 $('.container .component .container') .filter(function() {return $(this).css('width') == 'auto';}) .css({border: '1px solid #f00'}); 
 $(".container .component").each(function() { if ($(".container", this).css('width') === "auto") $(".container", this).css('border', '1px solid #f00'); });