jQuery:你可以通过 CSS 规则而不是类来选择吗?
-
09-06-2019 - |
题
一个 .container 可以包含许多 .components,并且 .components 本身可以包含 .containers(而 .container 又可以包含 .components 等)。ETC。)
给定这样的代码:
$(".container .component").each(function(){
$(".container", this).css('border', '1px solid #f00');
});
我需要在大括号内的行中添加什么才能仅选择 CSS 中宽度设置为“auto”的嵌套 .containers?我确信这很简单,但我还没有真正使用过 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');
});
不隶属于 StackOverflow