在DOM元素中直接绑定
1 <a href="#" id="btn1" onclick="hello()">点击按钮</a> 2 <script> 3 function hello() { 4 alert('hello world'); 5 } 6 </script>
在JavaScript代码中绑定
使JS代码与hrml标签分离,文档结构清晰,便于开发和管理
1 <a href="#" id="btn1">点击按钮</a> 2 <script> 3 document.getElementById('btn1').onclick = function () { 4 alert('hello world'); 5 } 6 </script>
使用事件监听绑定及移出
(1)IE标准(IE8及其以下版本)
绑定
语法:element.attachEvent(event,function)
event : (必需)事件类型,需要加“on”
function:(必需)指定事件触发时执行的函数
1 <a href="#" id="btn1">点击按钮</a> 2 <script> 3 document.getElementById('btn1').attachEvent('onclick', function () { 4 alert('hello world'); 5 }) 6 </script>
事件处理函数中,this代表的是window对象
移出
语法:element.detachEvent(event,function)
(2)W3C规范(不支持IE8及以下版本)
语法:element.addEventListener(event,function,useCapture)
event : 不需要加“on”
useCapture:(可选)指定事件是否在捕获或冒泡截断进行。true,捕获。false,冒泡。默认false。
1 <a href="#" id="btn1">点击按钮</a> 2 <script> 3 document.getElementById('btn1').addEventListener('click', function () { 4 alert('hello world'); 5 }) 6 </script>
事件处理函数中,this代表dom对象
移出:
语法:element.removeEventListener(event,function,useCapture)
(3)封装事件监听
1 <a href="#" id="btn1">点击按钮</a> 2 <script> 3 //绑定 4 function addEventHandler(target, type, fn) { 5 if (target.addEventListener) { 6 target.addEventListener(type, fn); 7 } else { 8 target.attachEvent('on' + type, fn); 9 } 10 } 11 //移除 12 function removeEventHandler(target, type, fn) { 13 if (target.removeEventListener) { 14 target.removeEventListener(type, fn); 15 } else { 16 target.detachEvent('on' + type, fn); 17 } 18 } 19 //测试 20 var btn = document.getElementById('btn1'); 21 function hello() { 22 alert('hello world'); 23 } 24 addEventHandler(btn, 'click', hello); 25 removeEventHandler(btn, 'click', hello); 26 </script>
(4)事件监听的优点
- 可以绑定多个事件
1 var btn = document.getElementById('btn1'); 2 btn.onclick = function () { 3 alert('hello1') 4 }; 5 btn.onclick = function () { 6 alert('hello2'); 7 }
上述代码只弹出了hello2。也就是只执行了第二个函数
1 var btn = document.getElementById('btn1'); 2 btn.addEventListener('click', function () { 3 alert('hello1'); 4 }) 5 btn.addEventListener('click', function () { 6 alert('hello2'); 7 })
上述代码两个函数都能执行
特殊例子,绑定同一个事件处理函数,并且都是事件冒泡或者事件捕获类型,那么只能绑定一次。
1 <a href="#" id="btn">点击按钮</a> 2 <script> 3 var btn = document.getElementById('btn'); 4 function a() { 5 alert(1); 6 } 7 btn.addEventListener('click', a, false); 8 btn.addEventListener('click', a, false); 9 //点击btn后,只会弹出一次1 10 </script>
匿名函数之间即使代码完全一样,也是互不相同的。
- 可以解除相应的绑定
如果要解除相应的绑定,那么绑定的事件不能使用匿名函数,必须将事件处理函数单独写成一个函数,否则无法取消。