2013-03-26 72 views
-2

我有幾個具有相同類名稱的div。但有不同的內容。他們就像如下JQuery:迭代相同的類名稱

<div class="schoolLib"> 
     <div class="message"> 
      <span class="msgTextLib">This is a sample text.</span> 
     </div> 
    </div> 


    <div class="schoolCanteen"> 
     <div class="message"> 
      <span class="msgTextcanteen">This is another sample text.</span> 
     </div> 
    </div> 


    <div class="schoolBus"> 
     <div class="message"> 
      <span class="msgTextBus">This is a sample text for Bus.</span> 
     </div> 
    </div> 

我怎樣才能使用的.html進去消息類的DIV中的所有文本()。我的內容正在動態發展。我有不同的跨班級。另外我需要使用.html()爲所有div設置不同的文本。所以我需要一種方法來迭代地獲取類名消息下的所有內容。我知道.each()方法,但不知道如何做到這一點。作爲初學者,我需要你的幫助。我會很感激你的幫助。

+0

太基本了,請使用Google關於如何使用'.each()'。另外這裏是jQuery文檔... http://api.jquery.com/jQuery.each/ – Dom 2013-03-26 16:57:30

回答

0

您可以使用each來遍歷集合:

$('.message').each(function(){ 
    var msg = $(this); 
    msg.html('<div> new content </div>'); //for adding html 
    //or to set the text use 
    msg.text('change text'); 
    }); 
0

正如評論指出的使用。每()獲取內容。僅供您參考張貼摘錄。

var html = ''; 
    $('.message').each(function(){ 
     html += $(this).html(); //get the html 
     $(this).html('<span>something else</span>') //set a different html 
    }); 
    console.log(html); 
0

試試這個,如果你總是隻有一個跨度爲每條消息:( '消息'),

每個$(函數(){

警報($(本)。兒童。 ().first()。text());

});

我不知道你想要做什麼與郵件內容,但與此你可以得到所有的人。 如果你想你可以將它們存儲在一個數組中,並在其他上下文中使用...