开发者

Why don't even handlers of dynamically inserted objects fire, even if they existed before the JavaScript ran?

I working on a client side app. I have been working non-stop for the past two days trying to figure what was going on. My code is a bit too long to post to where I can explain what my problem is, I have narrowed where the problem is to the following scenario/question. Here is what I have:

<html>
    <head>
    </head>
    <body>
        <a href="#" id="hyper">Link</a>
    </body>
</body>
</html>
<script type="text/javascript">
    document.getElementById("hyper").onclick = function(){alert("Link clicked!");};
    document.body.innerHTML = document.body.innerHTML;
</script>

This code works fine with out the without document.body.innerHTML = document.body.innerHTML;.

Why doesn't the event handler fire after body.innerHTML = body.innerHTML; even though the object, ob开发者_高级运维ject.id are still the same and have loaded before the JavaScript?

I have viewed the live DOM and all is the same.


When you re-assign body.innerHTML, even if it's itself, the innerHTML changes and the DOM resets. That means, the a#hyper was re-created and its onclick became destroyed.

Self-assignment identity (note: said as a Haskeller) may not exist with getters and setters.\


There is a great answer here - basically the DOM is regenerated when Javascript re-inserts the HTML string. The generated DOM may look the same, but programmatic references in Javascript have all been set to new addresses.

A solution for keeping event handlers and methods is here:

javascript cloneNode and properties

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜