2011-08-18 58 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。这是一个有用的方法:) –