以下五种方式添加事件
<!doctype html> <html> <head> <title>事件处理程序的执行上下文</title> <meta charset="utf-8"> <style> div { background: gold; margin: 10px; } </style> </head> <body> <!-- 内联事件代码 --> <div id="d1" onclick="alert(this.tagName)">DIV1</div> <!-- 内联一个函数 --> <div id="d2" onclick="fn()">DIV2</div> <!-- DOM 0 --> <div id="d3">DIV3</div> <!-- DOM 2 --> <div id="d4">DIV4</div> <!-- IE低版本 --> <div id="d5">DIV5</div> <script> function $(id) {return document.getElementById(id)} var d1 = $('d1'), d2 = $('d2'), d3 = $('d3'), d4 = $('d4'), d5 = $('d5') // 事件处理程序 function fn() { if (this.tagName) { alert(this.tagName) } else { alert(this) } } // DOM 0 (All Browsers) d3.onclick = fn // DOM 2 (IE9/10, FF, Safari, Chrome, Opera) try { d4.addEventListener('click', fn, false) } catch(e) {} // 低版本IE (IE6/7/8, Opera) try { d5.attachEvent('onclick', fn) }catch(e){} </script> </body> </html>
结果如下:
- 内联HTML (element)
- 内联HTML fn (window)
- DOM-0级onXXX (element)
- DOM-2级addEventListener (element)
- IE低版本attachEvent (IE6/7/8: window, Opera: element)