Jquery 从单击中遍历HTML片段以获取范围的内容
我有下面的HTML(重复了很多次),希望在我单击href之前立即获取span的内容Jquery 从单击中遍历HTML片段以获取范围的内容,jquery,Jquery,我有下面的HTML(重复了很多次),希望在我单击href之前立即获取span的内容 <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="
<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>
编辑对不起,即使我在末尾添加了.text(),我也会得到NULL,我认为遍历不太正确。您可能想要
应该是
var count= $(this).parent("div").parent(".listitem").children(".votecount").text();
复制了您的代码,并使其与以下内容一起工作:
var count = $(this).parents().find(".votecount").text();
问题是在
p
元素中不能有div
。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>
22票
理查德·怀尔德
如您所见,p.listitem
不再是投票链接的父项。如果将p.listitem
更改为div.listitem
,则添加了.text()
的代码可以正常工作
我已将代码添加到演示中。请确保您准确复制了HTML。如果有输入错误,可能会弄乱渲染。请参阅我编辑的答案。复制了您的代码并使其工作,但解决方案没有多大意义…当您知道如何操作时,就很简单了!谢谢,我没有发现在P's里面有div的问题,这是有道理的。再换一个灯泡需要多少程序员?好地方。
var count= $(this).parent("div").parent(".listitem").children(".votecount").text();
var count = $(this).parents().find(".votecount").text();
<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>