This article mainly introduces the method of adding DOM nodes to documents in JavaScript, and compares and analyzes the two methods of node creation in JavaScript, involving related techniques of JavaScript node operation and running time calculation. Friends in need can refer to it. The details are as follows:
Here are two methods compared: the first one: create all nodes first, and then add them to the running time of the document; the second one: first add an empty container to the document, and then add each The running time of creating a node and then adding it to the container. From the test point of view, the second method is better than the first!
The operation effect is shown in the figure below:
The specific code is as follows:
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>将DOM节点添加到文档实例</title> </head> <script type="text/javascript"> //第一种:先创建所有节点,再添加到文档 function createAdd(count) { var start=new Date(); var container=document.createElement("p"); var obj=document.getElementById("main"); for(var i=0;i<count;i++) { var node=document.createElement("p"); node.style.position="absolute"; node.style.left=(6+parseInt(Math.random()*100))+"px"; node.style.top=(6+parseInt(Math.random()*100))+"px"; container.appendChild(node); } obj.appendChild(container); var end=new Date(); var duration=end-start; alert("第一种方式:"+duration+"ms"); } //第二种:先添加到文档一个空容器,再创建所有接点,并分别添加到容器中 function addCreate(count) { var start=new Date(); var container=document.createElement("p"); var obj=document.getElementById("main"); obj.appendChild(container); for(var i=0;i<count;i++) { var node=document.createElement("p"); node.style.position="absolute"; node.style.left=(6+parseInt(Math.random()*100))+"px"; node.style.top=(6+parseInt(Math.random()*100))+"px"; container.appendChild(node); } var end=new Date(); var duration=end-start; alert("第二种方式:"+duration+"ms"); } //检测输入的数据是否正确 function checkData() { var number=parseInt(document.getElementById("count").value); return number; } //调用createAdd()函数 function callCreateAdd() { var count=checkData(); createAdd(count); } //调用addCreate()函数 function callAddCreate() { var count=checkData(); addCreate(count); } </script> <body> <h3>将DOM节点添加到文档实例</h3> <hr style="border:1px solid #000000;" /> 请输入一个整数: <input type="text" id="count" name="count" /> <br /> <input type="button" id="createadd" name="createadd" value="第一种:先创建所有节点,再添加到文档方式的运行时长" onClick="callCreateAdd();" /> <input type="button" id="one" name="one" value="第二种:先向文档添加一个空容器,然后每创建一个节点,再添加到容器中方式的运行时长" onClick="callAddCreate();" /> <br /> <p id="main" style="position:absolute;"></p> </body> </html>
The above is the entire content of this chapter, more For related tutorials, please visit JavaScript Video Tutorial!