JQUERY load an array of elements into a DIV
I have an array of DIV elements in an array called 'noactiveMsg'.
I want to load these DIV elements into a DIV called $('#chatCenterMembers')
.
I've tried:
noactiveMsg.appendTo($('#chatCenterMembers'));
But this doesn't work. Can someone advice on the syntax to load an array of elements/objects into a div?
code to made the array:
var noactiveMsg=[];
$('div.chatmember').each(function() {
if($(this).children().children('div').hasClass('chatactivestatus_offline')) {
alert('offline');
noactiveMsg.push($(this));
} 开发者_Go百科
});
If each element of your array is a jQuery object, you can try this:
Some sample html:
<div>
<p>Some stuff below!</p>
</div>
The jQuery stuff:
$(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
I think this is the code you need. Assuming noactiveMsg is an array containing jQuery objects.
cnt = noactiveMsg.length();
for(i=0; i<cnt; i++) {
$('#chatCenterMembers').append(noactiveMsg[i].html());
}
You'll want to merge them all into one jQuery object:
var noactiveMsg = [$('<a>1</a>'), $('<a>1</a>')],
collection;
$.each(noactiveMsg, function(i, e) {
collection ? collection = collection.add(e) : collection = e;
});
EDIT:
Others have suggested adding every element in the array separately into the DOM. I would strongly advise you against it. Interacting with the DOM is an expensive operation, and should be avoided whenever possible.
精彩评论