2013-03-26 61 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());

});

我不知道你想要做什么与邮件内容,但与此你可以得到所有的人。 如果你想你可以将它们存储在一个数组中,并在其他上下文中使用...

相关问题