初學JavaScript時,會用這樣的方法監聽事件
<html>
<head>
<meta charset="utf-8">
<title>js事件監聽機制</title>
</head>
<body>
<input type="button" value="click me!" id="btn-1">
<script type="text/javascript">
btn1 = document.getElementById("btn-1");
btn1.onclick = function(){
alert("第一次點擊按鈕");
}
btn1.onclick = function(){
alert("第二次點擊按鈕");
}
</script>
</body>
</html>
然而和想象中的結果並不相同,當點擊按鈕時,彈出窗口這樣顯示
這是因爲當同一個對象用.onclick觸發多個寫法時,後面的方法會把前面的覆蓋掉,當事件發生時,只會執行最後的綁定方法,在上面的例子中,後面的方法把前面的覆蓋了,所以只出現了一個窗口。
對於這種現象,我們可以用以下的方式來解決
1.addEventListener
語法
target.addEventListener(type, listener, useCapture);
target:文檔節點
type:事件名稱,不含on,例如click,keydown
listener:調用的函數
useCapture:是否綁定在捕獲階段,默認爲falsel
示例代碼
<html>
<head>
<meta charset="utf-8">
<title>js事件監聽機制</title>
</head>
<body>
<input type="button" value="click me!" id="btn-1">
<script type="text/javascript">
function eventFirst(){
alert("第一次點擊按鈕");
}
function eventSecond(){
alert("第二次點擊按鈕");
}
window.onload = function(){
btn1 = document.getElementById("btn-1");
btn1.addEventListener("click", eventFirst);
btn1.addEventListener("click", eventSecond);
}
</script>
</body>
</html>
當點擊按鈕時,出現如下情況
點擊確定
依次輸出第一個監聽事件和第二個監聽事件
解除事件綁定
<span style="font-size:18px;">btn1.removeEventListener("click", eventFirst);</span>
這樣就解除了第一個監聽事件的綁定
當點擊按鈕時,只輸出第二個監聽事件
注意:解除事件綁定時一定要用函數的句柄,否則解綁無效
2.attachEvent
IE瀏覽器使用attachEvent來綁定事件
語法
target.attachEvent(type, listener);
target:文檔節點
type:事件名稱,帶on,比如onclick,onkeydown等等
listener:調用的函數
3.兼容各大主流瀏覽器的寫法
通過以上的實驗,最終對函數進行封裝
代碼如下
<html>
<head>
<meta charset="utf-8">
<title>js事件監聽機制</title>
<style type="text/css">
#box{
height:100px;
width:100px;
background-color:red;
}
</style>
</head>
<body>
<div id="box">
<input type="button" value="click me!" id="btn-1">
</div>
<script type="text/javascript">
//監聽元素事件函數
function addEventHandler(target, type, func){
if(target.addEventListener){
//兼容IE9,Firefox以及Chrome
target.addEventListener(type, func, false);
}else if(target.attachEvent){
//版本較低的IE瀏覽器
target.attachEvent("on" + type, func);
}else{
target["on" + type] = func;
}
}
//解除事件監聽
function removeEventHandler(target, type, func){
if(target.removeEventListener){
target.removeEventListener(type, func, false);
}else if(target.detachEvent){
target.detachEvent("on" + type, func);
}else{
delete target["on" + type];
}
}
function eventFirst(){
alert("點擊按鈕");
}
function eventSecond(){
alert("點擊div");
}
window.onload = function(){
btn1 = document.getElementById("btn-1");
box1 = document.getElementById("box");
//給按鈕添加監聽事件
addEventHandler(btn1, "click", eventFirst);
//給div添加監聽事件
addEventHandler(box, "click", eventSecond);
//解除div的監聽事件
removeEventHandler(box, "click", eventSecond);
}
</script>
</body>
</html>