我有 2 个隐藏的 DIV
每个DIV都包含一个SPAN
我只想显示具有 RedBackground 类 SPAN 的 DIV
我编写的 JavaScript 代码无法正常工作
$("div span.RedBackground").show();
.greenBackground {
color: green;
}
.RedBackground {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="display: none;">
<span class="RedBackground">show this</span>
</div>
<div style="display: none;">
<span class="GreenBackground">NOT show this</span>
</div>
最佳答案
使用:has
selector获取包含该元素的所有 div
。不需要使用诸如 parent
或 closest
之类的东西:
$("div:has(span.RedBackground)").show();
.greenBackground { color: green; }
.RedBackground { color: red; }
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="display: none;">
<span class="RedBackground">show this</span>
</div>
<div style="display: none;">
<span class="GreenBackground">NOT show this</span>
</div>
关于jquery - 显示具有特定 CSS 类的子元素的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45233428/