通过单击遍历HTML片段以获取范围的内容

时间:2011-10-11 14:52:09

标签: jquery

我有以下HTML(重复多次),并希望在我点击的href之前获取范围的内容。

<p class="listitem">
  <img src="./1.jpg" alt="" width="50" height="50"/>
  <span class="votecount">22</span> Votes
  <span class="name">Richard Wilde</span>
  <a href="ViewEntry.aspx?Id=1019">View Entry</a>
  <div id="id-1"><a href="#" rel="vote-1019" >...</a></div>
</p>

我也有以下jquery,我试图用22填充计数,但似乎无法计算出这个。

$("a[rel^='vote']").click(function () {
  var id = ($(this).attr("rel")).replace("vote-", "");
  $(this).unbind("click");
  var count= $(this).parent("div").parent(".listitem").children(".votecount");
  return false;
}); 

编辑抱歉,即使我在最后添加.text()我得到NULL,我认为遍历不太正确。

4 个答案:

答案 0 :(得分:4)

问题是您不能在divp元素。 div是结构元素,而p用于包含文本,因此它没有意义。您的浏览器(或者至少是我的Chrome)正在重写您的HTML,如下所示:

<p class="listitem">
   <img src="./1.jpg" alt="" width="50" height="50"/>
   <span class="votecount">22</span> Votes
   <span class="name">Richard Wilde</span>
   <a href="ViewEntry.aspx?Id=1019">View Entry</a>
</p>
<div id="id-1"><a href="#" rel="vote-1019" >...</a></div>
<p></p>

正如您所看到的,p.listitem不再是投票链接的父级。如果您将p.listitem更改为div.listitem,那么添加.text()的代码将按预期工作。

我已将代码添加到jsbin以进行演示。

答案 1 :(得分:1)

您可能想要text function

$(this).parent().parent().children('.votecount').text()

答案 2 :(得分:1)

复制你的代码,并使用它:

var count = $(this).parents().find(".votecount").text();

答案 3 :(得分:0)

var count= $(this).parent("div").parent(".listitem").children(".votecount");

应该是

var count= $(this).parent("div").parent(".listitem").children(".votecount").text();