2013-08-01 34 views
4
var data='<div class="shout_msg"> 
    <span class="username">3</span> 
    <span class="message">hello</span> 
</div> 
<div class="shout_msg"> 
    <span class="username">0</span> 
    <span class="message">yo</span> 
</div> 
<div class="shout_msg"> 
    <span class="username">0</span> 
    <span class="message">hey</span> 
</div> 
<div class="shout_msg"> 
    <span class="username">0</span> 
    <span class="message">haha</span> 
</div>'; 

$(data).find(".shout_msg").each(function(index){ 
    console.log($(this).find("span.username").text()); 
}); 

它沒有返回任何東西。基本上,這裏顯示的數據來自AJAX請求。但無論如何,我正在犯一個愚蠢的錯誤或什麼。請糾正我。查找指定類別的每個div

+1

如果它來自阿賈克斯,你爲什麼不使用JSON來傳輸數據?它會讓事情變得更簡單! – MightyPork

回答

5

你會想在這種情況下使用filter,因爲你不在對象內部搜索。

$(data).filter(".shout_msg").each(function(index){ 
    console.log($(this).find("span.username").text()); 
}); 

下面是您的快速演示。

http://jsbin.com/ocefeq/1/edit

+0

謝謝比爾。真的很感激快速的迴應! –

+0

沒問題!很高興我能幫上忙。 –

+0

順便把這個標記爲答案是可以的! –

2

你都應該使用filter這裏

$(data).filter(".shout_msg"). 

您需要訪問元素的第一級,卻發現將努力讓不包括當前級別的元素,讓後代代替。

Check Fiddle

+0

非常感謝Sushant,您的快速幫助確實讓我的一天變得更加美好! –

+0

很高興有幫助:) –