2011-08-18 25 views
1

我在一個名爲'noactiveMsg'的數組中有一個DIV元素數組。 我想將這些DIV元素加載到名爲$('#chatCenterMembers')的DIV中。JQUERY將元素數組加載到DIV中

我已經試過:

noactiveMsg.appendTo($('#chatCenterMembers')); 

但是,這是行不通的。 可以有人建議的語法加載元素/對象數組到一個div?

代碼所做的數組:

var noactiveMsg=[]; 
$('div.chatmember').each(function() {       
if($(this).children().children('div').hasClass('chatactivestatus_offline')) { 
alert('offline'); 
noactiveMsg.push($(this)); 
}    
}); 
+2

DIV數組是如何創建的?每個數組元素都是一個單獨的jQuery對象嗎?提供一個實際的代碼示例,這個問題將隨時爲您解答。 –

+0

我添加了代碼來創建數組... thx – Adam

+0

你仍然沒有向我們展示'noactiveMsg'的初始化位置。它是否包含任何元素在它到達此節之前? –

回答

1

如果陣列中的每個元素是一個jQuery對象,你可以試試這個:


一些樣品的html:

<div> 
    <p>Some stuff below!</p> 
</div> 

jQuery的東西:

$(function(){ 
    var foo = []; 
    foo.push($('<p>hello</p>')); 
    foo.push($('<p>world</p>')); 
    foo.push($('<p>Adam</p>')); 

    // this will fail because each element is a 
    // separate jQuery object 
    // $('div').append(foo); 

    // instead try this 
    $.each(foo, function(){ 
     $('div').append(this); 
    }) 
}); 

see it work on jsFiddle

I also answered a similar question just recently

0

我覺得這是你所需要的代碼。 假設noactiveMsg是一個包含jQuery對象的數組。

cnt = noactiveMsg.length();

for(i=0; i<cnt; i++) {

$('#chatCenterMembers').append(noactiveMsg[i].html()); 

}

0

你會想他們都合併到一個jQuery對象:

var noactiveMsg = [$('<a>1</a>'), $('<a>1</a>')], 
    collection; 

$.each(noactiveMsg, function(i, e) { 
    collection ? collection = collection.add(e) : collection = e; 
}); 

編輯:

也有人建議將每一個元素在數組中分別int DOM。我強烈建議你不要這樣做。與DOM交互是一項昂貴的操作,應儘可能避免。

+0

你好@Joseph Silber,你能教給我一些關於'.add()'方法嗎?這是原生的JavaScript?它究竟做了什麼? –

+0

@macek。簡單地說:如果你想將兩個jQuery集合合併成一個,你可以使用jQuery的add()方法。這不會修改原始集合。它會返回一個新集合,其中包含這兩個集合中的所有元素:http://api.jquery.com/add/ –

+0

Thans @Joseph。這是一個有用的方法:) –