appendChild仅适用于第一次 [英] appendChild only works first time

查看:115
本文介绍了appendChild仅适用于第一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过同一页面上的按钮和事件处理程序重复向元素添加相同的内容。

I want to repeatedly append the same stuff to an element via a button and event handler on the same page.

我遇到的问题是它只是第一次工作。它完全符合我想要的第一次,然后在后续按钮按下时无法执行任何操作。我有点蠢蠢欲动,似乎在第一次追加之后,newstuff.innerHTML被清空了。经过多次徒劳无功的搜索,我决定来这里问。

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. After much fruitless searching, I decided to come and ask here.

事件处理程序正在触发,变量的innerHTML被追加,但我不能为我的生活解决了为什么我的变量被破坏了。

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.

下面的变量和数据已被更改以保护无辜者。

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);
    }
}


推荐答案

这是因为DOM节点只能存在于DOM中的一个位置。当您调用 lineitems.appendChild(newstuff.firstChild)时,它会将其从原始位置移除并将其添加到新位置。这意味着它只能工作一次。

This is because a DOM node can only exist in one place in the DOM. When you call lineitems.appendChild(newstuff.firstChild), it is removing it from the original place and adding it to the new location. 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;
};

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

这篇关于appendChild仅适用于第一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆