2010-02-23 57 views
17

有兩種將HTML代碼添加到DOM的方法,我不知道最好的方法是什麼。應該使用innerHTML將HTML添加到DOM還是逐個創建新元素?

第一種方法

第一種方法是最簡單的一個,我可以簡單地添加使用$('[code here]').appendTo(element); HTML代碼(使用jQuery),這一點很像element.innerHTML = [code here];

方法二

另一種方法是逐個創建所有元素,例如:

// 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.createElementelement.setAttribute

什麼時候應該使用第一種方法,何時使用第二種方法?方法二比方法一更快嗎? -

編輯的speed tests

我的確從該代碼如下三種速度的測試結果:

$(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; 
    }); 
}); 

這給了下面的真正令人驚訝的結果

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

總而言之innerHTML方法似乎是最快的,在很多情況下是最可讀的方法。

回答

2

我指出一個過時的article爲人們測試它自己的目的。 DOM方法實際上擊敗了我所有機器上的innerHTML,所以我更喜歡它。然而,在文章的時候,innerHTML在平均時更快。目前這種差異只能在巨大的數據集中才能看到。

+1

速度不是唯一的問題......通常情況下,像'第一種方法'寫的代碼將比'第二種方法更具可讀性。 – 2010-02-23 15:57:07

0

如果我要在代碼的後面重新使用div,我會構建它並將它放在一個var中,通常帶有$前綴,所以我知道它是一個jQuery對象。如果這是一個一次性的事情,我會只是做一個:

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

其實,無論是方法使用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 + "></" + tag + ">"; 
    }); 
    // etc... 
} 

一般來說,使用的innerHTML比操縱DOM慢,因爲它調用HTML解析器(其將解析HTML到DOM反正)。

相關問題