【问题标题】:Cloned element is not shown未显示克隆元素
【发布时间】:2017-08-26 13:06:52
【问题描述】:

以下代码应克隆给定元素并将其插入到之后:

function cloneMore(element) {
    var newElement = element.cloneNode(true);
    element.parentNode.insertBefore(newElement, element.nextSibling);
}
var addChoice = document.getElementById("add-choice")
addChoice.onclick = (function(){cloneMore(document.getElementById("choices").lastChild);})

html 看起来像这样:

<ul id="choices">
    <!-- form elements -->
</ul>
<p><a id="add-choice">Add another choice</a></p>

没有抛出异常,一切都执行了,但我看不到新元素。为什么?

【问题讨论】:

  • 控制台记录它,看看它是否正在克隆

标签: javascript html clone


【解决方案1】:

lastChild 选择所有节点类型,而不仅仅是元素。所以你可能正在克隆一个 TextNode \n

我猜你想要的是lastElementChild

function cloneMore(element) {
  var newElement = element.cloneNode(true);
  element.parentNode.insertBefore(newElement, element.nextSibling);
}
var addChoice = document.getElementById("add-choice")
addChoice.onclick = function() {
  var choices = document.getElementById("choices");
  cloneMore(choices.lastElementChild); // only Elements
  console.log('lastChild type : ', choices.lastChild.nodeName); 
}
<ul id="choices">
  <li> choice </li>
</ul>
<p><a href="#" id="add-choice">Add another choice</a></p>

【讨论】:

    猜你喜欢
    • 2015-03-19
    • 2016-02-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    • 1970-01-01
    • 2013-01-26
    • 1970-01-01
    • 2011-04-23
    相关资源
    最近更新 更多