我有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>
&#13;
答案 0 :(得分:2)
使用: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>
答案 1 :(得分:0)
$("span.RedBackground").parent('div')
来显示div。表示隐藏的span.RedBackground
的父div显示$("div span.RedBackground").show();
表示div为span.RedBackground
,但div被隐藏,因此您仍然无法看到任何closest("div")
$("span.RedBackground").parent('div').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>