關於邦定事件失效的問題。

來源:互聯網
上載者:User

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

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.