【问题标题】:my way of cloning html node does not work我克隆 html 节点的方式不起作用
【发布时间】:2015-12-08 14:11:49
【问题描述】:

我是初学者 java 脚本学习者,并遵循一些在线教程来改进。 我不太明白为什么我的代码不起作用,当我打开 chrome 开发人员工具时我没有看到任何错误?如果有人能告诉我我在这里做错了什么,我将不胜感激。 登录后我发现我意识到在var the_node= document.getElementById("hh").lastChild; 中,the_node 仍然是未定义的

<doctype! html>
<html>
<head>
    <title>clone a node</title>
    <script>
        function cloneNode1() {
            var the_node= document.getElementById("hh").lastChild;
            var cloned_node = the_node.cloneNode(true);
            document.getElementById("hh").appendChild(cloned_node);
        }   
    </script>
</head>
<body>
    <h1>welcome to Sarah's page</h1>
    <h2>here is the list of things which I really like</h2>
    <ul id="hh">
        <li>painting</li>
        <li>cooking</li>
    </ul>
    <p>click on the buttom to add to the list</p>
    <button onclick="cloneNode1()"> click me to colne</button>
</body>
</html>

【问题讨论】:

    标签: javascript html


    【解决方案1】:

    问题在于element.lastChild无论是元素节点、文本节点还是评论节点都返回最后一个子节点。在您的情况下,它返回包含换行符的文本节点。元素内的空白被视为文本,文本被视为节点。

    为了更清楚,如果您删除 hh 元素中的所有空格,它将起作用:

    function cloneNode1() {
      var the_node= document.getElementById("hh").lastChild;
      var cloned_node = the_node.cloneNode(true);
      document.getElementById("hh").appendChild(cloned_node);
    }   
    <ul id="hh"><li>painting</li><li>cooking</li></ul>
    <button onclick="cloneNode1()"> click me to colne</button>

    但是,您不需要这样做。如果要提取最后一个子元素,只需使用 element.lastElementChild

    这里是sn-p,改方法后生效:

    function cloneNode1() {
      var the_node= document.getElementById("hh").lastElementChild;
      var cloned_node = the_node.cloneNode(true);
      document.getElementById("hh").appendChild(cloned_node);
    }   
    <ul id="hh">
      <li>painting</li>
      <li>cooking</li>
    </ul>
    <button onclick="cloneNode1()"> click me to colne</button>

    【讨论】:

      猜你喜欢
      • 2011-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-27
      • 1970-01-01
      相关资源
      最近更新 更多