有兩種將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.createElement
和element.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方法似乎是最快的,在很多情況下是最可讀的方法。
速度不是唯一的問題......通常情況下,像'第一種方法'寫的代碼將比'第二種方法更具可讀性。 – 2010-02-23 15:57:07