问题
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. 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.
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);
}
}
回答1:
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;
};
See http://jsfiddle.net/LAKkQ/
回答2:
I think appendChild
will actually move firstChild
, not clone it. 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.
来源:https://stackoverflow.com/questions/8981145/appendchild-only-works-first-time