关于邦定事件失效的问题。
昨天在项目中碰到一个问题,当执行document.body.innerHTML += '....',页面上所在DOM上邦定的事件全部失效了,幸好有同事阿杜和小袁帮助,问题才得以解决。举例说明一下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> <script type="text/javascript"> window.onload = function() { var test1 = document.getElementById('test1'); var oJoin = document.getElementById('join'); test1.onclick = function() { alert(this.innerHTML); } oJoin.onclick = function() { document.body.innerHTML += '<p>test2</p>'; //当执行这个后,页面上所有DOM上所邦定的事件全部失效了。 } } </script> </head> <body> <p id="test1">test1</p> <a href="#" id="join">join</a> </body> </html>
运行上面的代码,当单击test1时可以正常执行预定的函数,但当你点击join之后,运行相当的函数,再接你再点击test1看看,邦定在这个DOM上的函数不在执行了,因为document.body.innerHTML +='<p>test2</p>';解决方法就是用appendChild;
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> <script type="text/javascript"> window.onload = function() { var test1 = document.getElementById('test1'); var oJoin = document.getElementById('join'); test1.onclick = function() { alert(this.innerHTML); } oJoin.onclick = function() { var div = document.createElement('div'); //首先创建一个div; div.innerHTML = '<p>test2</p>'; //然后将你想创建的结构代码用innerHTML的形式存入div中。 document.body.appendChild(div) //这样就不会出现事件失效的问题了 } } </script> </head> <body> <p id="test1">test1</p> <a href="#" id="join">join</a> </body> </html>