看到Chrome DevTools中的節點數量,我想知道在單擊Button1之後單擊Button1以及單擊Button2之後dom樹中的差異。
'innerHTML'和'appendChild'之間的區別
的index.html
<html>
<head>
<script src="./js/main.js" type="text/javascript" charset="utf-8"></script>
<link rel="stylesheet" href="style/default.css">
</head>
<body>
<div id="buttons">
<div class="button" id="button1">Execute1</div>
<div class="button" id="button2">Execute2</div>
</div>
<div id="main"></div>
<div id="main2"></div>
</body>
</html>
main.js
document.addEventListener("DOMContentLoaded", function() {
var button1 = document.getElementById('button1');
button1.addEventListener('click', function() {
document.getElementById('main').innerHTML += '<div>hello</div>';
});
var button2 = document.getElementById('button2');
button2.addEventListener('click', function() {
var div = document.createElement('div');
div.appendChild(document.createTextNode('hello2'));
document.getElementById('main2').appendChild(div);
});
});
default.css
#buttons {
display:-webkit-flex;
align-items: center;
}
.button {
height: 30px;
width: 100px;
margin: 5px;
background-color: #0080C0;
color: #FFFFFF;
display:-webkit-flex;
align-items: center;
justify-content: center;
cursor: pointer;
}
當我點擊Button1的,節點的數量由4
增加但是,當我點擊按鈕2,節點的數量由2
被2遞增遞增有道理的我,因爲他們可能是一個'div'元素和文本節點'hello2'。
但是,單擊Button1,還要添加哪些其他節點?
一個使用DOM和另一個瀏覽器功能。 – DanMan
相關:http://stackoverflow.com/questions/2305654/innerhtml-vs-appendchildtxtnode – mehlon