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

Ada*_*ton 24 javascript jquery css-selectors

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

给出这样的代码:

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

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

Dav*_*lin 19

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

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


小智 19

你可能想要研究一下.filter().

就像是:

$('.container .component .container')
.filter(function() {return $(this).css('width') == 'auto';})
.css({border: '1px solid #f00'});
Run Code Online (Sandbox Code Playgroud)