“innerHTML”和“appendChild”之间的区别

2023-11-23

观察 Chrome DevTools 中的节点数量,我想知道单击 Button1 后的 dom 树和单击 Button2 后的 dom 树有什么区别。

索引.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);
    });
} );

默认.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;
}

When I click the Button1, the number of nodes is incremented by 4.
But when I click the button2, the number of nodes is incremented by 2.
Be incrementing by 2 makes sense for me as they could be a 'div' element and a text node 'hello2'.
But clicking the Button1, what other nodes be appended?

enter image description here


Using appendChild将新的 DOM 元素添加到父节点的末尾。

Using innerHTML +=获取父节点的现有 DOM 内容,将其序列化为字符串中的 HTML,在字符串末尾添加更多 HTML,擦除父节点中的现有元素,从该字符串生成 DOM 元素,然后附加新节点到父节点。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

“innerHTML”和“appendChild”之间的区别 的相关文章

随机推荐