HTML ..

<div class="row">
   <div>
      <b>Title A</b> <a href="#">Link 1</a> <a href="#">Link 2</a>
   </div>
   Content A
</div>
<div class="row">
   <div>
      <b>Title B</b> <a href="#">Link 1</a> <a href="#">Link 2</a>
   </div>
   Content B
</div>
<div class="row">
   <div>
      <b>Title C</b> <a href="#">Link 1</a> <a href="#">Link 2</a>
   </div>
   Content C
</div>

的jQuery ..

到目前为止,我的JS添加了一个<!>“Link 3 <!>”;在每个<!>之后链接;链接2 <!>“; ..

$("a:contains('Link 2')").each(function(){
   $(this).after(' <a href="#">Link 3</a>');
});

对于循环中的每个项目,我如何访问标题。

$("a:contains('Link 2')").each(function(){
   // I need to find the title string for each row. So is there a way to find elements before the $(this) identifier?
   $(this).after(' <a href="#">Link 3</a>');
});
有帮助吗?

解决方案

您可以使用 .prev()方法获取之前的兄弟姐妹。您可以这样做,或者您可以获取 .parent()链接,然后 .find()第一个<b>标签。

<p>Something Here</p> <!-- This becomes red -->
<p class="pickme">Hello World</p>

$(document).ready(function(){
  $(".pickme").prev().css("color","red");
});

<p>Something Here</p> <!-- this becomes green -->
<p class="pickme">Hello World</p>

$(document).ready(function(){
  $(".pickme").parent().find("p:first").css("color", "green");
});

其他提示

如果你添加一个类,例如<!> quot; rowTitle <!> quot;对于包装标题的所有粗体标签,您应该能够:

$("a:contains('Link 2')").each(function(){
   $(this).parent().find(".rowTitle").html
});

或类似的东西。 jQuery Docs 相当全面,在那里快速搜索可以帮助您找到自己的内容寻找。

我不是jQuery专家,但我相信这非常接近于工作。也许对这个问题更精通的人可以详细说明我的答案(因为我不介意学习)。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top