Har*_*men 17 javascript jquery dom createelement
将HTML代码添加到DOM有两种方法,我不知道最好的方法是什么.
第一种方法
第一种方式是简单的方法,我可以简单地添加HTML代码(使用jQuery)$('[code here]').appendTo(element);,这很像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);
Run Code Online (Sandbox Code Playgroud)
此方法使用核心功能,如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($('<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;
});
});
Run Code Online (Sandbox Code Playgroud)
这给了以下非常令人惊讶的结果
Test One Test Two Test Three
+-------------+---------+----------+------------+
| Chrome 5 | ~125ms | ~10ms | ~15ms |
| Firefox 3.6 | ~365ms | ~35ms | ~23ms |
| IE 8 | ~828ms | ~125ms | ~15ms |
+-------------+---------+----------+------------+
Run Code Online (Sandbox Code Playgroud)
总而言之,innerHTML方法似乎是最快的方法,并且在许多情况下是最可读的方法.
| 归档时间: |
|
| 查看次数: |
4702 次 |
| 最近记录: |