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
标签中带有相同文本的组中event
的每个第一个实例提供了一个a
类。
现在,我希望每当我单击clicker
时,都希望所有具有相同.event
文字的.event .title a
div重新出现。
(更新了代码以显示正确的结构以及为什么该解决方案不起作用。每当我单击“ clicker”时,它将代码应用于所有事件)
答案 0 :(得分:2)
您需要将click事件附加到event
类,然后当用户单击div时,您可以获得锚点的文本,并使用contains
选择器过滤具有相同标题的事件文字:
$('.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>