Javascript jQuery附加一个元素数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12111740/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:07:51  来源:igfitidea点击:

jQuery appending an array of elements

javascriptjqueryarraysperformanceappend

提问by George Reith

For the purpose of this question lets say we need to append()1000 objects to the bodyelement.

出于这个问题的目的,假设我们需要append()1000 个对象到body元素。

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:

这有效,但对我来说似乎效率低下,因为 AFAIK 这将导致 1000 次文档回流。更好的解决方案是:

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.

然而,这不是一个理想的世界,这会引发错误Could not convert JavaScript argument arg 0 [nsIDOMDocumentFragment.appendChild]。我知道append()无法处理数组。

How would I using jQuery(I know about the DocumentFragmentnode, 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(我知道DocumentFragment节点,但假设我需要在元素上使用其他 jQuery 函数,例如.css())一次向 DOM 添加一堆对象以提高性能?

回答by Felix Kling

You could use an empty jQuery object instead of an array:

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

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

如果您想在循环内使用新生成的元素执行操作,这可能很有用。但请注意,这将创建一个巨大的内部元素堆栈(在 jQuery 对象内部)。



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

看起来你的代码在 jQuery 1.8 上工作得很好

回答by jAndy

You could just call

你可以打电话

$('body').append(elements.join(''));

Or you can just create a large string in the first place.

或者您可以首先创建一个大字符串。

var elements = '';
for(x = 0; x < 1000; x++) {
    elements = elements + '<div>'+x+'</div>';
}
$(document.body).append(elements);

Like you mentioned, probably the most "correct" way is the usage of a DocFrag. This could look like

就像您提到的那样,可能最“正确”的方法是使用 DocFrag。这可能看起来像

var elements = document.createDocumentFragment(),
    newDiv;
for(x = 0; x < 1000; x++) {
    newDiv = document.createElement('div');
    newDiv.textContent = x;
    elements.append( newDiv );
}
$(document.body).append(elements);

.textContentis not supported by IE<9 and would need an conditional check to use .innerTextor .textinstead.

.textContentIE<9 不支持,需要条件检查才能使用.innerText.text

回答by Jethro Larson

Since $.fn.append takes a variable number of elements we can use applyto pass the array as arguments to it:

由于 $.fn.append 接受可变数量的元素,我们可以apply用来将数组作为参数传递给它:

el.append.apply(el, myArray);

This works if you have an array of jQuery objects. According to the spec though you can append an array of elements if you have the DOM elements. If you have an array of html strings you can just .join('') them and append them all at once.

如果您有一组 jQuery 对象,这将起作用。根据规范,如果您有 DOM 元素,则可以附加一个元素数组。如果你有一个 html 字符串数组,你可以 .join('') 它们并一次附加它们。

回答by Alexey Lebedev

Upgrade to jQuery 1.8, this works as intended:

升级到 jQuery 1.8,这按预期工作:

?$('body')?.append([
    '<b>1</b>',
    '<i>2</i>'   
])?;?

回答by Dog

A slight change to your second approach:

对您的第二种方法略有改动:

var elements = [],
newDiv;
for (x = 0; x < 1000; x++) {
    newDiv = $('<div/>').text(x);
    elements.push(newDiv);
}
$('body').append(elements);

$.append() certainly can append an array: http://api.jquery.com/append/

$.append() 当然可以追加一个数组:http: //api.jquery.com/append/

.append(content) | content: One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements.

.append(内容) | 内容:一个或多个附加 DOM 元素、元素数组、HTML 字符串或 jQuery 对象,以插入匹配元素集中每个元素的末尾。

回答by Hymanwanders

Sometimes, jQuery isn't the best solution. If you have a lot of elements to append to the DOM, documentFragmentis a viable solution:

有时,jQuery 并不是最好的解决方案。如果您有很多元素要附加到 DOM,这documentFragment是一个可行的解决方案:

var fragment = document.createDocumentFragment();
for(var i = 0; i < 1000; i++) {
    fragment.appendChild(document.createElement('div'));
}
document.getElementsByTagName('body')[0].appendChild(fragment);

回答by shaedrich

I know, the question is old, but maybe it helps others.

我知道,这个问题很老,但也许对其他人有帮助。

Or simple use ECMA6 spread operator:

或者简单使用 ECMA6 扩展运算符:

$('body').append(...elements);

回答by davids

I would use native Javascript, normally much faster:

我会使用原生 Javascript,通常要快得多:

var el = document.getElementById('the_container_id');
var aux;
for(x = 0; x < 1000; x++) {
    aux = document.createElement('div');
    aux.innerHTML = x;
    el.appendChild(aux);
}

EDIT:

编辑:

There you go a jsfiddlewith different options implemented. The @Hymanwander's solution is, clearly, the most effective one.

在那里,您可以使用实现不同选项的jsfiddle。@Hymanwander 的解决方案显然是最有效的解决方案。

回答by MalSu

If you're going for raw performance then I would suggest pure JS, though some would argue that your development performance is more important than your site's/program performance. Check this linkfor benchmarks and a showcase of different DOM insertion techniques.

如果您追求原始性能,那么我会建议使用纯 JS,尽管有些人会争辩说您的开发性能比您的站点/程序性能更重要。检查此链接以获取基准测试和不同 DOM 插入技术的展示。

edit:

编辑:

As a curiosity, documentFragmentproves to be one of the slowest methods.

作为一种好奇,被documentFragment证明是最慢的方法之一。