jQuery:我们可以通过CSS规则而不是类进行选择吗?
时间:2020-03-05 18:47:39 来源:igfitidea点击:
一个.container可以包含许多.component,而.components本身可以包含.container(它们又可以包含.component等)。
给定这样的代码:
$(".container .component").each(function(){ $(".container", this).css('border', '1px solid #f00'); });
我需要在花括号内的行中添加哪些内容,以仅选择在CSS中将其宽度设置为"自动"的嵌套.container?我敢肯定这很简单,但是我并没有真正使用jQuery。
解决方案
回答
$(".container .component").each(function() { if ($(".container", this).css('width') === "auto") $(".container", this).css('border', '1px solid #f00'); });
回答
$(".container .component").each(function() { $(".container", this).each(function() { if($(this).css('width') == 'auto') { $(this).css('border', '1px solid #f00'); } }); });
与其他答案类似,但是由于组件也可以具有多个容器,因此在这里也需要.each()来检查宽度。