问题描述
我正在重构一些旧的JavaScript代码,并且有很多DOM操作正在进行。
var d = document;
var odv = d.createElement(div);
odv.style.display =none;
this.OuterDiv = odv;
var t = d.createElement(table);
t.cellSpacing = 0;
t.className =text;
odv.appendChild(t);
我想知道是否有更好的方法来使用jQuery。我一直在尝试:
var odv = $ .create(div);
$ .append(odv);
//还有更多
但我不知道这是否更好。
这是您在一个行中的示例。
这个$ OuterDiv = $('< div>< / div>')
.hide()
.append($('< table> ; / table>')
.attr({cellSpacing:0})
.addClass(text)
)
;
更新:我以为我会更新这篇文章,因为它仍然有相当多的流量。在下面的评论中,有关 $(< div>)
vs $(< div>< / div>) )
vs $(document.createElement('div'))
作为创建新元素的方法,它是最好的。 p>
我将放在一起,大概的结果重复上述选项100,000次:
jQuery 1.4,1.5,1.6
Chrome 11 Firefox 4 IE9
< div> 440ms 640ms 460ms
< div>< / div> 420ms 650ms 480ms
createElement 100ms 180ms 300ms
jQuery 1.3 / p>
Chrome 11
< div> 770ms
< div>< / div> 3800ms
createElement 100ms
jQuery 1.2
Chrome 11
< div> 3500ms
< div>< / div> 3500ms
createElement 100ms
我认为这不是什么大惊喜,但是 document.createElement
是最快的方法。当然,在您开始重构整个代码库之前,请记住,我们在这里讨论的差异(除了jQuery的古老版本之外)等同于每千个元素额外的3毫秒。
更新2
更新为jQuery 1.7.2,并将基准JSBen.ch这可能比我的原始基准更加科学,加上现在可以拥挤!
I'm refactoring some old JavaScript code and there's a lot of DOM manipulation going on.
var d = document;
var odv = d.createElement("div");
odv.style.display = "none";
this.OuterDiv = odv;
var t = d.createElement("table");
t.cellSpacing = 0;
t.className = "text";
odv.appendChild(t);
I would like to know if there is a better way to do this using jQuery. I've been experimenting with:
var odv = $.create("div");
$.append(odv);
// And many more
But I'm not sure if this is any better.
here's your example in "one" line.
this.$OuterDiv = $('<div></div>')
.hide()
.append($('<table></table>')
.attr({ cellSpacing : 0 })
.addClass("text")
)
;
Update: I thought I'd update this post since it still gets quite a bit of traffic. In the comments below there's some discussion about $("<div>")
vs $("<div></div>")
vs $(document.createElement('div'))
as a way of creating new elements, and which is "best".
I put together a small benchmark, and here's roughly the results of repeating the above options 100,000 times:
jQuery 1.4, 1.5, 1.6
Chrome 11 Firefox 4 IE9
<div> 440ms 640ms 460ms
<div></div> 420ms 650ms 480ms
createElement 100ms 180ms 300ms
jQuery 1.3
Chrome 11
<div> 770ms
<div></div> 3800ms
createElement 100ms
jQuery 1.2
Chrome 11
<div> 3500ms
<div></div> 3500ms
createElement 100ms
I think it's no big surprise, but document.createElement
is the fastest method. Of course, before you go off and start refactoring your entire codebase, remember that the differences we're talking about here (in all but the archaic versions of jQuery) equate to about an extra 3 milliseconds per thousand elements.
Update 2
Updated for jQuery 1.7.2 and put the benchmark on JSBen.ch which is probably a bit more scientific than my primitive benchmarks, plus it can be crowdsourced now!
这篇关于jQuery document.createElement等效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!