下面是我正在尝试做的事情的原型(prototype)。
var entry_set = $;
// start to loop data
for([])
{
// create HTML element to represent that data
$('<div></div>')
.data([])
.addClass([])
.on([])
.insertAfter(entry_set);
}
// modify DOM only once all the entries are consolidated to a single jQuery object
entry_set.appendTo('.entries');
评论说明了一切。简而言之 - 这个想法是在插入数据时仅修改文档 DOM 一次。我通常会采用 HTML 字符串方法(简单地使用字符串连接相同的结构),但我感兴趣的是与此类似的任何方法是否也可以工作。
最佳答案
您可以创建一个空的 DOM 元素并对其进行 .append()
var entry_set = $("<div>"); //empty dom element
// start to loop data
var i = 4;
while(i--) {
// create HTML element to represent that data
var item = $('<div>', {
text: "test " + i
});
entry_set.append(item);
}
// modify DOM only once all the entries are consolidated to a single jQuery object
$("body").append(entry_set.children());
工作演示:http://jsfiddle.net/F2J6g/1/
编辑 您还可以从一个空集合开始并使用 .add()
var entry_set = $(); //empty collection
// start to loop data
var i = 4;
while(i--) {
// create HTML element to represent that data
var item = $('<div>', {
text: "test " + i
});
entry_set = entry_set.add(item);
}
// modify DOM only once all the entries are consolidated to a single jQuery object
$("body").append(entry_set);
关于dom - 连接 jQuery 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10498839/