2011-10-11 21 views
2

我有以下HTML(多次重複),並希望在我點擊的href之前立即獲取span的內容。從點擊中遍歷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> 
    <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(),我覺得遍歷並不完全正確。

+0

請參閱我編輯的答案。複製你的代碼,並得到它的工作,但解決方案沒有多大意義.... –

回答

4

的問題是,你不能有div內部p元素。 A div是一個結構元素,而p用於包含文本,因此它沒有任何意義。您的瀏覽器(或至少鉻對我來說)正在改寫你的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來演示。

+0

簡單,當你知道如何!謝謝,未能發現在P的 – Rippo

+0

中有div的問題,這很有道理。有多少程序員需要再次更換燈泡?好點。 –

1

你可能想在text function

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

對不起,請參閱編輯,我總是得到NULL,遍歷是錯誤的 – Rippo

+0

請確保您已經完全複製您的HTML。如果出現拼寫錯誤,可能會搞亂渲染 – zzzzBov

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

應該

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

對不起,請參閱編輯,我總是得到NULL,遍歷是錯的 – Rippo

1

複製你的代碼,並得到了其與這方面的工作:

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