如果div中的锚包含前一个div中的锚文本,则运行jQuery

Xan*_*der 0 jquery

这在jQuery中甚至可能吗?

基本上我有两个div

<div class="first">
    <a href="#">Some random link</a>, 
    <a href="#">second random link</a>, 
    <a href="#">other random link</a>
</div>
<div class="second">
    <a href="#">second random link</a>
    <a href="#">third random link</a>
    <a href="#">tenth random link</a>
</div>
Run Code Online (Sandbox Code Playgroud)

我想要的是如果第二个div中的锚中的文本与第一个div中的锚中的文本匹配(每个页面上不同),则运行jQuery(将类添加到包含匹配文本的第二个div中的锚点) ).

Bar*_*mar 5

用于$.each()在第二个DIV中循环锚点.然后,您可以测试其文本是否位于第一个DIV中的任何锚点中.

$("#doit").click(function() {
  $(".second a").each(function() {
    var text = $(this).text();
    if ($(".first a:contains(" + text + ")").length) {
      $(this).addClass("matched");
    }
  });
});
Run Code Online (Sandbox Code Playgroud)
.matched {
  color: green;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="first">
  <a href="#">Some random link</a>,
  <a href="#">second random link</a>,
  <a href="#">other random link</a>
</div>
<div class="second">
  <a href="#">second random link</a>
  <a href="#">third random link</a>
  <a href="#">tenth random link</a>
</div>
<button id="doit">Click to test</button>
Run Code Online (Sandbox Code Playgroud)