Example: The effect we want to achieve is to append some new data to the old data when the user clicks the mouse.
If you use the standard DOM, the complete code is as follows:
Copy code code as follows:
<title>test</title>
<body>
<div>
<p>data<p>
</div>
<script>
Document.onmousedown = function () {
for (var i = 0; i < i++) {
var p = document.createelement ("P");
P.appendchild (document.createTextNode (Math.random ()));
document.getElementsByTagName (' div ') [0].appendchild (P);
}
};
</script>
</body>
Note: Once the structure is more complex, the standard DOM needs to write lengthy code.
If you use innerHTML, some of the code is as follows:
Copy code code as follows:
<script>
Document.onmousedown = function () {
var html = "";
for (var i = 0; i < i++) {
HTML + + "<p>" + math.random () + "<p>";
}
document.getElementsByTagName (' div ') [0].innerhtml + + html;
};
</script>
Note: innerHTML does not have a standard DOM appendchild, so use the "+ +" approach, inefficient.
We can combine the innerHTML and the standard DOM so that the advantages of both are both, and some of the code is as follows:
Copy code code as follows:
<script>
Document.onmousedown = function () {
var html = "";
for (var i = 0; i < i++) {
HTML + + "<p>" + math.random () + "<p>";
}
var temp = document.createelement ("div");
temp.innerhtml = html;
while (Temp.firstchild) {
document.getElementsByTagName (' div ') [0].appendchild (Temp.firstchild);
}
};
</script>
Note: Create an element, then inject innerHTML, then use standard DOM operations on the element.
Still not finished, asynchronous innerHTML gave a more robust solution, some of the code is as follows:
Copy code code as follows:
<script>
Document.onmousedown = function () {
var html = "";
for (var i = 0; i < i++) {
HTML + + "<p>" + math.random () + "<p>";
}
var temp = document.createelement (' div ');
temp.innerhtml = html;
var frag = document.createdocumentfragment ();
(function () {
if (temp.firstchild) {
Frag.appendchild (Temp.firstchild);
settimeout (Arguments.callee, 0);
} else {
document.getElementsByTagName (' div ') [0].appendchild (Frag);
}
})();
};
</script>
Note: Use settimeout to prevent clogging of browsers, and use documentfragment to reduce rendering times.