MAO-EYE 2008-11-06 12:26 采纳率: 100%
浏览 331
已采纳

创建元素等价吗?

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.

转载于:https://stackoverflow.com/questions/268490/jquery-document-createelement-equivalent

  • 写回答

13条回答 默认 最新

  • 喵-见缝插针 2008-11-06 12:34
    关注

    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!

    http://jsben.ch/#/ARUtz

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(12条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!