Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
488 views
in Technique[技术] by (71.8m points)

javascript - 是否可以在不破坏后代事件侦听器的情况下附加到innerHTML?(Is it possible to append to innerHTML without destroying descendants' event listeners?)

In the following example code, I attach an onclick event handler to the span containing the text "foo".(在以下示例代码中,我将onclick事件处理程序附加到包含文本“ foo”的范围。)

The handler is an anonymous function that pops up an alert() .(该处理程序是一个匿名函数,会弹出alert() 。) However, if I assign to the parent node's innerHTML , this onclick event handler gets destroyed - clicking "foo" fails to pop up the alert box.(但是,如果我将其分配给父节点的innerHTML ,则此onclick事件处理程序将被销毁-单击“ foo”将无法弹出警报框。) Is this fixable?(这个可以解决吗?) <html> <head> <script type="text/javascript"> function start () { myspan = document.getElementById("myspan"); myspan.onclick = function() { alert ("hi"); }; mydiv = document.getElementById("mydiv"); mydiv.innerHTML += "bar"; } </script> </head> <body onload="start()"> <div id="mydiv" style="border: solid red 2px"> <span id="myspan">foo</span> </div> </body> </html>   ask by mike translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Unfortunately, assignment to innerHTML causes the destruction of all child elements, even if you're trying to append.(不幸的是,即使您试图追加,对innerHTML赋值也会破坏所有子元素。)

If you want to preserve child nodes (and their event handlers), you'll need to use DOM functions :(如果要保留子节点(及其事件处理程序),则需要使用DOM函数 :) function start() { var myspan = document.getElementById("myspan"); myspan.onclick = function() { alert ("hi"); }; var mydiv = document.getElementById("mydiv"); mydiv.appendChild(document.createTextNode("bar")); } Edit: Bob's solution, from the comments.(编辑:鲍勃的解决方案,从评论。) Post your answer, Bob!(发表您的答案,鲍勃!) Get credit for it.(为此获得信誉。) :-)(:-)) function start() { var myspan = document.getElementById("myspan"); myspan.onclick = function() { alert ("hi"); }; var mydiv = document.getElementById("mydiv"); var newcontent = document.createElement('div'); newcontent.innerHTML = "bar"; while (newcontent.firstChild) { mydiv.appendChild(newcontent.firstChild); } }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...