将 jQuery 元素数组附加到页面的最佳方式是什么?
我知道,如果我直接附加 HTML 标签,那么它们应该一起收集在一个数组中,然后附加该数组。这是最快的方法。不过,我有一个 jQuery 元素集合,这些元素上创建了事件,所以我不能只是将字符串连接在一起。
示例:
function displayCommentActions(actions) {
var html = [];
module.$element.find('.comments .actions li').remove();
$.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);
})
};
这很丑陋,因为它需要两个循环。一种用于创建 jQuery 对象,另一种用于将它们输出到页面。如何改进我的代码?
最佳答案
@efritz,对每个列表项执行 .remove() 既缓慢又昂贵,快速删除列表项将是 .empty()。
@Samuel 你无法避免在这里循环。 .append() 接受一个字符串(html)或一个 jquery 对象。它不能接受 jquery 对象数组。
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>
}
这可能和你能得到的一样小,Samuel,它至少是对你的双循环的改进。
关于javascript - 将 jQuery 元素数组插入页面的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3341171/