问题描述
对于这个问题,假设我们需要 append()
1000 个对象到 body
元素.
你可以这样做:
for(x = 0; x '+x+'');$('body').append(元素);}
这有效,但对我来说似乎效率低下,因为 AFAIK 这将导致 1000 次文档回流.更好的解决方案是:
var elements = [];for(x = 0; x '+x+'');元素推(元素);}$('body').append(elements);
然而,这不是一个理想的世界,这会引发错误无法转换 JavaScript 参数 arg 0 [nsIDOMDocumentFragment.appendChild]
.我知道 append()
不能处理数组.
我将如何使用 jQuery
(我知道 DocumentFragment 节点,但假设我需要在元素上使用其他 jQuery 函数例如 .css()
) 一次向 DOM 添加一堆对象以提高性能?
您可以使用空的 jQuery 对象而不是数组:
var elements = $();for(x = 0; x
如果您想在循环内使用新生成的元素执行操作,这可能很有用.但请注意,这将创建一个巨大的内部元素堆栈(在 jQuery 对象内部).
For the purpose of this question lets say we need to append()
1000 objects to the body
element.
You could go about it like this:
for(x = 0; x < 1000; x++) {
var element = $('<div>'+x+'</div>');
$('body').append(element);
}
This works, however it seems inefficient to me as AFAIK this will cause 1000 document reflows. A better solution would be:
var elements = [];
for(x = 0; x < 1000; x++) {
var element = $('<div>'+x+'</div>');
elements.push(element);
}
$('body').append(elements);
However this is not an ideal world and this throws an error Could not convert JavaScript argument arg 0 [nsIDOMDocumentFragment.appendChild]
. I understand that append()
can't handle arrays.
How would I using jQuery
(I know about the DocumentFragment node, but assume I need to use other jQuery functions on the element such as .css()
) add a bunch of objects to the DOM at once to improve performance?
You could use an empty jQuery object instead of an array:
var elements = $();
for(x = 0; x < 1000; x++) {
elements = elements.add('<div>'+x+'</div>');
// or
// var element = $('<div>'+x+'</div>');
// elements = elements.add(element);
}
$('body').append(elements);
This might be useful if you want to do stuff with newly generated element inside the loop. But note that this will create a huge internal stack of elements (inside the jQuery object).
It seems though that your code works perfectly fine with jQuery 1.8.
这篇关于jQuery附加一个元素数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!