JS中使用innerHTML和createElement方式动态创建元素
方式一:使用innerHTML拼接字符串方式
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>innerHTML拼接字符串方式</title> <style> div { width: 1000px; } </style> <script> window.onload = function() { var div = document.querySelector('div'); var time1 = +new Date(); for (var i = 0; i < 1000; i++) { div.innerHTML += '<a href="javaScript:;">链接</a>\t'; } var time2 = +new Date(); console.log(time2 - time1); } </script></head><body> <div></div></body></html>
运行结果:
方式二:innerHTML加数组的方式
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>innerHTML加数组的方式</title> <style> div { width: 1000px; } </style> <script> window.onload = function() { var div = document.querySelector('div'); var arr = []; var time1 = +new Date(); for (var i = 0; i < 1000; i++) { arr.push('<a href="javaScript:;">链接</a>\t') } div.innerHTML = arr.join(''); var time2 = +new Date(); console.log(time2 - time1); } </script></head><body> <div></div></body></html>
运行结果:
方式三:createElement方式
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>createElement方式</title> <style> div { width: 1000px; } </style> <script> window.onload = function() { var div = document.querySelector('div'); var time1 = +new Date(); for (var i = 0; i < 1000; i++) { var a = document.createElement('a'); a.innerHTML = '链接'; a.href = 'javaScript:;'; div.appendChild(a); } var time2 = +new Date(); console.log(time2 - time1); } </script></head><body> <div></div></body></html>
运行结果:
总结:
innerHTML方式创建多个元素的时候效率会更高,但是不能使用字符串拼接的方式,使用字符串拼接的时候会不断开辟新的内存,所以时间长,可以使用数组的方式。createElement在创建多个元素的时候效率较低,但是结构更清晰。声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。