gpt4 book ai didi

javascript - jQuery 将类添加到包含类元素的 div

转载 作者:行者123 更新时间:2023-11-30 08:22:03 25 4
gpt4 key购买 nike

我有一个像这样的简单布局...

<div class="container">
<div class="row" id="234">
<div class="left special">
This is left content
</div>
<div class="right">
This is right content
</div>
</div>
<div class="row" id="944">
<div class="left">
This is left content
</div>
<div class="right">
This is right content
</div>
</div>
<div class="row" id="332">
<div class="left">
This is left content
</div>
<div class="right special">
This is right content
</div>
</div>
</div>

我正在尝试使用 jQuery 仅针对其中包含 special 类的行 ID。到目前为止我有这个

jQuery( ".row:has(.special)" ).addClass( "test" );

但是它没有添加test类,我哪里错了?

最佳答案

您可以在这里简单地使用.has 方法,将一个类添加到所有具有类special 的元素中:

$(".row").has(".special").addClass("test");
.test{color:red}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="row" id="234">
<div class="left special">
This is left content special
</div>
<div class="right">
This is right content
</div>
</div>
<div class="row" id="944">
<div class="left">
This is left content
</div>
<div class="right">
This is right content
</div>
</div>
<div class="row" id="332">
<div class="left">
This is left content
</div>
<div class="right special">
This is right content special
</div>
</div>
</div>

关于javascript - jQuery 将类添加到包含类元素的 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51920407/

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