gpt4 book ai didi

jquery - 显示具有特定 CSS 类的子元素的元素

转载 作者:行者123 更新时间:2023-12-01 08:42:58 24 4
gpt4 key购买 nike

我有 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 。不需要使用诸如 parentclosest 之类的东西:

$("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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com