如何使用jQuery将多个相同的元素添加到div

问题描述:

我需要使用jQuery将多个空div添加到容器元素中。

I need to add multiple empty divs to a container element using jQuery.

此刻,我使用循环生成一个包含空HTML的字符串

At the moment I am generating a string containing the empty html using a loop

divstr = '<div></div><div></div>...<div></div>';

然后将其注入到我的容器中:

and then injecting that into my container:

$('#container').html(divstr);

是否有更优雅的方式插入多个相同的元素?

Is there a more elegant way to insert multiple, identical elements?

我希望找到一些不会打破链接但不会使浏览器瘫痪的东西。可链接的 .repeat()插件?

I'm hoping to find something that wouldn't break chaining but wouldn't bring the browser to its knees. A chainable .repeat() plugin?

要快速 - 或者通常考虑速度,那么您需要在插入之前首先建立一个DOM片段。

If you want IE to be fast - or generally consider speed, then you'll want to build up a DOM fragment first before inserting it.

John Resig解释了该技术,并包含了性能基准:

John Resig explains the technique and includes a performance benchmark:

http://ejohn.org/ blog / dom-documentfragments /

var i = 10, 
    fragment = document.createDocumentFragment(), 
    div = document.createElement('div');

while (i--) {
    fragment.appendChild(div.cloneNode(true));
}

$('#container').append(fragment);

我意识到在构建片段时并没有大量使用jQuery,运行几个测试,我似乎不能做$(fragment).append() - 但是我已经看过John的jQuery 1.3版本应该包含基于上面所研究的更改。

I realise it's not making a lot of use of jQuery in building up the fragment, but I've run a few tests and I can't seem to do $(fragment).append() - but I've read John's jQuery 1.3 release is supposed to include changes based on the research linked above.