html添加到dom,javascript – 应该使用innerHTML将HTML添加到DOM还是逐个创建新元素?...

有两种方法可以将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方法似乎是最快的,在许多情况下是最可读的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值