您是应该使用innerHTML将DOM添加到DOM还是逐个创建新元素?

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

第一种方法

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

第二种方法

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

 // New div-element var div = $('
', { id: 'someID', class: 'someClassname' }); // New p-element that appends to the previous div-element $('

', { class: 'anotherClassname', text: 'Some textnode', }).appendTo(div);

此方法使用element.setAttributeelement.setAttribute等核心函数。

我何时应该使用第一种方法,何时使用第二种方法? 方法二比方法一快吗?

编辑 – 速度测试的结果

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

 $(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($('

', {'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 += '

number' + i + '

'; } inhere.innerHTML = el; endTimer(); return false; }); });

这给出了以下非常令人惊讶的结果

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

总而言之,innerHTML方法似乎是最快的方法,并且在许多情况下是最易读的方法。

我指的是一篇过时的文章 ,目的是让人们自己测试一下。 DOM方法实际上击败了我所有机器上的innerHTML,这就是我喜欢的。 然而,在文章的时候,innerHTML的平均速度更快。 目前,差异只能在庞大的数据集中大量出现。

实际上,两种方法都不使用innerHTML ,在这两种情况下,jQuery都将HTML转换为DOM节点。 来自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 + ">"; }); // etc... } 

一般来说,使用innerHTML比操作DOM要慢,因为它调用HTML解析器(无论如何都会将HTML解析为DOM)。

如果我将在代码中稍后重新使用div,我将构建它并将其放在var中,通常使用$前缀,所以我知道它是一个jquery对象。 如果这是一次性的事我会做一个:

  $('body').append(the stuff)