Best way to insert an array of jQuery elements to the page
What's the best way of appending an array of jQuery elements to the page?
I know that if I'm appending straight HTML tags then they should be collected together in an array then the array appended. This is the fastest method. However I have a collection of jQuery elements that have events created on them so I can't just concatenate strings together.
Example:
function displayCommentActions(actions) {
var html = [];
module.$element.find('.comments .actions li').remo开发者_如何学JAVAve();
$.each(actions, function(key, value) {
html.push($('<li class="' + key + '"><a href="#">' + value.name + '</a></li>').bind({
click: function(event) {
alert('found click');
}
}));
});
$.each(html, function(count, item) {
module.$element.find('.comments .actions').append(item);
})
};
This is ugly because it takes two loops. One to create the jQuery objects and one to output them to the page. How can I improve my code?
@efritz, doing .remove() on every list item is slow and expensive, a quick wipe of list items would be .empty().
@Samuel you can't avoid looping here. .append() takes either a string (of html) or a jquery object. It can't take an array of jquery objects.
var actionsList = module.$element.find('.comments .actions');
actionsList.empty() // Remove all contents of our <UL>
$.each(actions, function(class, value) {
var listItem = $('<li />').addClass(class) // Create our <li> and add our class
.append('<a href="javascript:void(0);">' + value.name + '</a>') // Add our link
.click(function() { // Click bind event
alert('Clicked item');
});
actionsList.append(listItem); // Add our <li> to our <ul>
}
This is probably as small as you're gonna get it Samuel, it's an improvement from your dual-loop at least.
Would something like this not work?
function displayCommentActions(actions) {
var target = module.$element.find('.comments .actions li')
target.remove();
$.each(actions, function(k, v) {
var item = $('<li />').addClass(key);
var link = $('<a />')
.attr('href', 'javascript:void(0);')
.html(value.name)
.click(function() {
alert('found click');
});
elem.append(item);
target.append(item);
}
}
Also, remember that repeated selectors can be expensive - store them if at all possible.
精彩评论