jQuery的附加元件的阵列 [英] jQuery appending an array of elements

查看:97
本文介绍了jQuery的附加元件的阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关这个问题的目的,可以说,我们需要() 1000对象追加到元素。

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);
}

这工作,但似乎没有效率的,我作为AFAIK这将导致1000笔回流。一个更好的解决办法是:

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);

然而,这并不是一个理想的世界,这将引发一个错误无法转换的JavaScript参数arg 0 nsIDOMDocumentFragment.appendChild] 。据我所知,追加()不能处理数组。

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.

我将如何使用的jQuery (我了解的DocumentFragment 节点,但是假设我需要的元素上使用其他jQuery的功能,如的.css())一次添加一堆对象的DOM来提高性能?

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?

推荐答案

您可以使用一个空的jQuery对象而不是数组的:

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);

如果你想要做的东西与循环中新生成的元素,这可能是有用的。但是请注意,这将创建元素的庞大的内部栈(jQuery的对象中)。

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).

看来虽然这您code工作完全正常使用jQuery 1.8

It seems though that your code works perfectly fine with jQuery 1.8.

这篇关于jQuery的附加元件的阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆