JS 和 HTML - cloneNode() 不工作

JS and HTML - cloneNode() isn't working

以下代码按预期工作。

CloneNode.js

<!DOCTYPE html>
<html>
        <body>
            <script src="../js/CloneNode.js">
            function myFunction(){
                var the_node = document.getElementById("myList").lastChild;
                var the_clone = the_node.cloneNode(true);
                document.getElementById("myList").appendChild(the_clone);
                }
            </script>
            <ul id="myList">
            <li>Good morning</li>
            <li>Hello</li></ul>
            <p>Click on the button to CloneNode()</p>
            <button onclick = "myFunction()">Copy it!</button>
    </body>
</html>

它也适用于以下代码:

<ul id="myList"><li>Good morning</li>
<li>Hello</li></ul>

<ul id="myList"><li>Good morning</li><li>Hello</li></ul>

但是当我在上面的 HTML 代码中的 </ul> 之前输入换行符时,如下所示,我没有得到输出。因此,网页上没有添加 <li> 元素。

<ul id="myList">
<li>Good morning</li>
<li>Hello</li>
</ul>

HTML 代码中的缩进如何影响输出?或者有什么我错过的吗?

Element.lastChild returns TextNode节点和Element节点一样,查询时换行符解析为空TextNode,所以要无论如何让它工作,改变

var the_node = document.getElementById("myList").lastChild;

var the_node = document.getElementById("myList").lastElementChild;

`尝试将所有这些放在同一个函数中作为该函数的局部变量。

  1. const new_item = getElementById(elementID) // 要克隆的元素。
  2. const cln = new_Item.cloneNode(真);
  3. getElementById(elementID).appendChild(cln) // 您要向其添加新克隆的元素。

// 我在存在 3 的函数中声明并初始化了 1 和 2。`