昨天在項目中碰到一個問題,當執行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>