仅切换包含相同文本的div [英] Toggle only div containing same text
问题描述
HTML:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="event">
<div class="clicker">
click
</div>
<div class="title">
<a href="#">first event</a>
</div>
</div>
<div class="event">
<div class="clicker">
click
</div>
<div class="title">
<a href="#">first event</a>
</div>
</div>
<div class="event">
<div class="clicker">
click
</div>
<div class="title">
<a href="#">second event</a>
</div>
</div>
<div class="event">
<div class="clicker">
click
</div>
<div class="title">
<a href="#">second event</a>
</div>
</div>
<div class="event">
<div class="clicker">
click
</div>
<div class="title">
<a href="#">second event</a>
</div>
</div>
<div class="event">
<div class="clicker">
click
</div>
<div class="title">
<a href="#">second event</a>
</div>
</div>
这给了我一个 foo
的课程事件
的第一个实例,其中 a
标记具有相同的文本。
This gives me a foo
class for every first instance of event
in a group with the a
tag with the same text.
现在我想这样,每当我点击点击器
时,我想要所有 .event
div使用相同的 .event .title a
文本重新出现。
Now I would like that, whenever I click a clicker
, I want all the .event
divs with same .event .title a
text to reappear.
(更新代码以显示正确的结构和原因解决方案不起作用。每当我点击clicker时,它会将代码应用于所有事件。
(code updated to show proper structure and why the solution didn't work. whenever i click on "clicker", it applies the code to ALL events)
推荐答案
你需要将click事件附加到事件
类,然后当用户单击div时,您可以获取锚的文本并使用 contains
选择器使用相同的标题文本过滤事件:
You need to attach a click event to the event
class, then when the user clicks the div you could get the text of the anchor and use contains
selector to filter the event with the same title text :
$('.event').click(function() {
$('.event a:contains(' + $('a', this).text() + ')').closest('.event').toggleClass('foo');
});
.foo {
background-color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="event">
<div class="title">
<a href="#">first event</a>
</div>
</div>
<div class="event">
<div class="title">
<a href="#">first event</a>
</div>
</div>
<div class="event">
<div class="title">
<a href="#">second event</a>
</div>
</div>
<div class="event">
<div class="title">
<a href="#">second event</a>
</div>
</div>
<div class="event">
<div class="title">
<a href="#">second event</a>
</div>
</div>
<div class="event">
<div class="title">
<a href="#">second event</a>
</div>
</div>
这篇关于仅切换包含相同文本的div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!