根据其内容将类添加到特定元素
我试图根据其描述将特定类添加到列表项目中。但是,当我添加下面的脚本时,它将其添加到所有列表项目中,而不仅仅是具有特定描述的项目。
带有描述“红色”的列表项目应获得“红色”,列出带有描述“蓝色”的项目应获得“蓝色”类。
jQuery(document).ready( function($){
if ($('.tax-desc:contains("red")')) {
$(".taxonomy-list-item").addClass("red");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="taxonomy-list-item">
<div class="tax-details">
<div class="tax-name">
<div class="tax-title">
<a href="#">Category 1</a>
</div></div><div class="tax-desc">Red</div>
</div>
</div>
<div class="taxonomy-list-item">
<div class="tax-details">
<div class="tax-name">
<div class="tax-title">
<a href="#">Category 2</a>
</div></div><div class="tax-desc">Blue</div>
</div>
</div>
I'm trying to add a specific class to a list item depending on its description. But when I add the script below, it adds it to all the list items, and not just those having that specific description.
List items with description "red" should get the class "red", list items with the description "blue" should get the class "blue".
jQuery(document).ready( function($){
if ($('.tax-desc:contains("red")')) {
$(".taxonomy-list-item").addClass("red");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="taxonomy-list-item">
<div class="tax-details">
<div class="tax-name">
<div class="tax-title">
<a href="#">Category 1</a>
</div></div><div class="tax-desc">Red</div>
</div>
</div>
<div class="taxonomy-list-item">
<div class="tax-details">
<div class="tax-name">
<div class="tax-title">
<a href="#">Category 2</a>
</div></div><div class="tax-desc">Blue</div>
</div>
</div>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果语句,您不需要
。使用
:has()
选择器可以使用此后代选择元素。:contains()
是个体敏感的,因此您需要red
而不是red
那里。You don't need an
if
statement. Use the:has()
selector to select the elements with this descendant.:contains()
is case-sensitive, so you needRed
rather thanred
there.