有两种方法可以将HTML代码添加到DOM中,我不知道最好的方法是什么。
第一种方法
第一种方法是简单的方法,我可以使用$(‘[code here])添加HTML代码(使用jQuery)。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);
此方法使用核心函数,如document.createElement和element.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($('
}
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方法似乎是最快的,在许多情况下是最可读的。