仅切换包含相同文本的div [英] Toggle only div containing same text

查看:78
本文介绍了仅切换包含相同文本的div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆