简体   繁体   English

appendChild仅在第一次工作

[英]appendChild only works first time

I want to repeatedly append the same stuff to an element via a button and event handler on the same page. 我想通过同一页面上的按钮和事件处理程序将相同的内容重复附加到元素上。

The problem I'm encountering is that it only works first time. 我遇到的问题是它只能在第一次使用。 It does exactly what I want the first time, then fails to do anything on subsequent button presses. 完全是我第一次想要的,但是随后的按键操作却无济于事。 I had a bit of a poke around, and it seems that after the first append, the "newstuff.innerHTML" is emptied. 我有点a,似乎在第一次追加之后,“ newstuff.innerHTML”被清空了。 After much fruitless searching, I decided to come and ask here. 经过无结果的搜索之后,我决定来这里询问。

The event handler is firing, the innerHTML of the variable is being appended, but I can't for the life of me work out why my variable is getting trashed. 事件处理程序正在触发,该变量的innerHTML被附加,但是我一生都无法弄清楚为什么我的变量被破坏了。

The variables and data below have been changed to protect the innocent. 下面的变量和数据已更改,以保护无辜者。

var button = document.getElementById('add_stuff');
var oldstuff = document.getElementById('element_id');
var newstuff = document.createElement('div');
newstuff.innerHTML = "<p>Super interesting content</p>";
button.onclick = function(event) {
    while (newstuff.firstChild) {
        oldstuff.appendChild(newstuff.firstChild);
    }
}

This is because a DOM node can only exist in one place in the DOM. 这是因为DOM节点只能存在于DOM中的一个位置。 When you call lineitems.appendChild(newstuff.firstChild) , it is removing it from the original place and adding it to the new location. 当您调用lineitems.appendChild(newstuff.firstChild) ,它会将其从原始位置删除并将其添加到新位置。 This means it will only work once. 这意味着它将只工作一次。

That being said, this would repeatedly add the markup like you want: 话虽如此,这将反复添加您想要的标记:

button.onclick = function(event) {
    lineitems.innerHTML += newstuff.innerHTML;
};

See http://jsfiddle.net/LAKkQ/ 参见http://jsfiddle.net/LAKkQ/

I think appendChild will actually move firstChild , not clone it. 认为 appendChild实际上会移动 firstChild ,而不是克隆它。 To clone it, you can use the cloneNode method on firstChild first, or get the HTML for firstChild and then use innerHTML again to append it. 要克隆它,你可以使用cloneNode的方法firstChild第一,或得到该HTML firstChild ,然后再使用innerHTML将其追加。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM