问题
I was messing around with some simple JS code and came across the following:
document.body.innerHTML += '<div id="div1">some text</div>';
var my_div = document.getElementById('div1');
document.body.innerHTML += '<div id="div2">some text</div>';
my_div.innerHTML = "some other text"; //doesn't work
It would seem that after manipulating the parent element (the body) the reference to the DOM node is invalidated. What am I doing wrong here?
回答1:
When you do this:
document.body.innerHTML += '<div id="div2">some text</div>';
it's the same as this:
document.body.innerHTML = document.body.innerHTML + '<div id="div2">some text</div>';
which as you can see replaces the whole of the body, recreating all the elements.
回答2:
You are not "manipulating" the innerHTML
, you are overwriting it!
When you use +=
on .innerHTML
the net result is that you end up serialising the entire DOM, appending the new string, and then deserialising the entire resulting HTML string back into DOM nodes. In the process, all existing DOM nodes get destroyed.
IMHO, you should never use .innerHTML
to manipulate DOM nodes, you should only use it to create them.
回答3:
you can use like this:
document.body.innerHTML += '<div id="div1">some text</div>';
var my_div = document.getElementById('div1');
var div2 = document.createElement('div');
div2.id = 'div2';
div2.innerHTML = 'some text';
my_div.parentNode.insertBefore(div2, my_div);
my_div.innerHTML = "some other text"; //work
回答4:
You should use like this, I think it will work fine.
<body>
</body>
<script type="text/javascript">
document.body.innerHTML += '<div id="div1">some text</div>';
var my_div = document.getElementById('div1');
document.body.innerHTML += '<div id="div2">some text</div>';
my_div.innerHTML = "some other text"; //doesn't work
</script>
来源:https://stackoverflow.com/questions/18329507/why-is-javascript-invalidating-dom-references-after-i-manipulate-the-bodys-inne