是否应该使用innerHTML将HTML添加到DOM中,或者逐个创建新元素? [英] Should you add HTML to the DOM using innerHTML or by creating new elements one by one?

查看:122
本文介绍了是否应该使用innerHTML将HTML添加到DOM中,或者逐个创建新元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有两种添加HTML代码到DOM中的方法,我不知道最好的方法是什么。

There are two methods to add HTML-code to the DOM and I don't know what is the best way to do it.

第一种方法

第一种方法是简单的方法,我可以使用 $('[代码]添加HTML代码(使用jQuery)这个]')。appendTo(element); 这很像 element.innerHTML = [code here];

The first way is the easy one, I could simply add HTML-code (with jQuery) using $('[code here]').appendTo(element); which is much like element.innerHTML = [code here];

第二种方法

另一种方法是逐个创建所有元素,如:

Another way is to create all the elements one by one like:

// New div-element
var div = $('<div/>', {
              id: 'someID',
              class: 'someClassname'
          });

// New p-element that appends to the previous div-element
$('<p/>', {
    class: 'anotherClassname',
    text: 'Some textnode',
}).appendTo(div);

此方法使用核心函数,如 document.createElement element.setAttribute

This method uses core functions like document.createElement and element.setAttribute.

什么时候应该使用第一种方法,第二种方法?方法比方法2快吗?

When should I use the first method and when the second? Is method two faster than method one?

编辑 - 速度测试

Edit - Result of speed tests

我做了三个速度测试,代码如下:

I did three speed tests from which the code follows:

$(document).ready(function(){
    // jQuery method - Above mentioned as the second method
    $('#test_one').click(function(){
        startTimer();
        var inhere = $('#inhere');
        for(i=0; i<1000; i++){
            $(inhere).append($('<p/>', {'class': 'anotherClassname' + i, text: 'number' + i}));
        }
        endTimer();
        return false;
    });

    // I thought this was much like the jQuery method, but it was not, as mentioned in the comments
    $('#test_two').click(function(){
        startTimer();
        var inhere = document.getElementById('inhere');
        for(i=0; i<1000; i++){
            var el = document.createElement('p')
            el.setAttribute('class', 'anotherClassname' + i);
            el.appendChild(document.createTextNode('number' + i));
            inhere.appendChild(el);
        }
        endTimer();
        return false;
    });

    // This is the innerHTML method
    $('#test_three').click(function(){
        startTimer();
        var inhere = document.getElementById('inhere'), el;
        for(i=0; i<1000; i++){
            el += '<p class="anotherClassname' + i + '">number' + i + '</p>';
        }                
        inhere.innerHTML = el;
        endTimer();
        return false;
    });
});

其中给了以下真正令人惊讶的结果

Which gave the following really surprising results

               Test One   Test Two   Test Three  
+-------------+---------+----------+------------+
| Chrome    5 | ~125ms  |  ~10ms   |   ~15ms    |
| Firefox 3.6 | ~365ms  |  ~35ms   |   ~23ms    |
| IE        8 | ~828ms  |  ~125ms  |   ~15ms    |
+-------------+---------+----------+------------+

所有的innerHTML方法似乎是最快的,在许多情况下最可读的一个。

All in all the innerHTML method seems to be the fastest one and is in many cases the most readable one.

推荐答案

实际上,两种方法都不使用 innerHTML 两种情况都是jQuery将HTML转换为DOM节点。从jquery-1.3.2.js:

Actually, neither methods use innerHTML, in both cases jQuery converts the HTML to DOM nodes. From jquery-1.3.2.js:

// If a single string is passed in and it's a single tag
// just do a createElement and skip the rest
if ( !fragment && elems.length === 1 && typeof elems[0] === "string" ) {
    var match = /^<(\w+)\s*\/?>$/.exec(elems[0]);
    if ( match )
        return [ context.createElement( match[1] ) ];
}

// ... some more code (shortened so nobody falls asleep) ...

// Convert html string into DOM nodes
if ( typeof elem === "string" ) {
    // Fix "XHTML"-style tags in all browsers
    elem = elem.replace(/(<(\w+)[^>]*?)\/>/g, function(all, front, tag){
        return tag.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i) ?
            all :
            front + "></" + tag + ">";
    });
    // etc...
}

一般来说,使用innerHTML比操纵DOM慢,因为它调用HTML解析器(这将解析HTML到DOM中)。

Generally speaking, using innerHTML is slower than manipulating the DOM, because it invokes the HTML parser (which will parse the HTML into the DOM anyway).

这篇关于是否应该使用innerHTML将HTML添加到DOM中,或者逐个创建新元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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