在JavaScript中,有三種常用的綁定事件的方法:
1.在DOM元素中直接綁定;
2.在JavaScript代碼中綁定;
3.綁定事件監(jiān)聽函數(shù)。
一. 原生函數(shù)
<input onclick="alert('謝謝支持')" type="button" value="點(diǎn)擊我,彈出警告框" />
或
<input onclick="myAlert()" type="button" value="點(diǎn)擊我,彈出警告框" />
<script type="text/javascript">
function myAlert(){
alert("謝謝支持");
}
</script>
二. 在JavaScript代碼中綁定
例如,為 id="demo" 的按鈕綁定一個(gè)事件,顯示它的 type 屬性:
<input id="demo" type="button" value="點(diǎn)擊我,顯示 type 屬性" />
<script type="text/javascript">
document.getElementById("demo").οnclick=function(){
alert(this.getAttribute("type"));
}
</script>
三. 綁定事件監(jiān)聽函數(shù)
綁定事件的另一種方法是用 addEventListener() 或 attachEvent() (兼容ie8)來綁定事件監(jiān)聽函數(shù)。
addEventListener()函數(shù)語法:
elementObject.addEventListener(eventName,handle,useCapture);
參數(shù)說明:
elementObject: DOM對(duì)象(即DOM元素)。
eventName: 事件名稱。注意,這里的事件名稱沒有“ on ”,如鼠標(biāo)單擊事件 click ,鼠標(biāo)雙擊事件 doubleclick ,鼠標(biāo)移入事件 mouseover,鼠標(biāo)移出事件 mouseout 等。
handle: 事件句柄函數(shù),即用來處理事件的函數(shù)。
useCapture: Boolean類型,是否使用捕獲,一般用false 。(默認(rèn)冒泡)
attachEvent()函數(shù)語法:(不支持捕獲)
elementObject.attachEvent(eventName,handle);
參數(shù)說明
elementObject: DOM對(duì)象(即DOM元素)。
eventName: 事件名稱。注意,與addEventListener()不同,這里的事件名稱有“ on ”,如鼠標(biāo)單擊事件 onclick ,鼠標(biāo)雙擊事件 ondoubleclick ,鼠標(biāo)移入事件 onmouseover,鼠標(biāo)移出事件 onmouseout 等。
handle: 事件句柄函數(shù),即用來處理事件的函數(shù)。
注意:事件句柄函數(shù)是指“ 函數(shù)名 ”,不能帶小括號(hào)。
addEventListener()是標(biāo)準(zhǔn)的綁定事件監(jiān)聽函數(shù)的方法,是W3C所支持的,Chrome、FireFox、Opera、Safari、IE9.0及其以上版本都支持該函數(shù);但是,IE8.0及其以下版本不支持該方法,它使用attachEvent()來綁定事件監(jiān)聽函數(shù)。所以,這種綁定事件的方法必須要處理瀏覽器兼容問題。
下面綁定事件的代碼,進(jìn)行了兼容性處理,能夠被所有瀏覽器支持:
function addEvent(obj,type,handle){
try{ // Chrome、FireFox、Opera、Safari、IE9.0及其以上版本
obj.addEventListener(type,handle,false);
}catch(e){
try{ // IE8.0及其以下版本
obj.attachEvent('on' + type,handle);
}catch(e){ // 早期瀏覽器
obj['on' + type] = handle;
}
}
}
這里使用 try{ … } catch(e){ … } 代替 if … else… 語句,避免瀏覽器出現(xiàn)錯(cuò)誤提示。
例如,為一個(gè) id="demo" 的按鈕綁定事件,鼠標(biāo)單擊時(shí)彈出警告框:
addEvent(document.getElementById("demo"),"click",myAlert);
function myAlert(){
alert("又是一個(gè)警告框");
}
四、自定義事件
var $ = function(el) {
return new _$(el);
};
var _$ = function(el) {
this.el = (el && el.nodeType == 1)? el: document;
};
_$.prototype = {
constructor: this,
addEvent: function(type, fn, capture) {
var el = this.el;
if (window.addEventListener) {
el.addEventListener(type, fn, capture);
var ev = document.createEvent("HTMLEvents");
ev.initEvent(type, capture || false, false);
if (!el["ev" + type]) {
el["ev" + type] = ev;
}
} else if (window.attachEvent) {
el.attachEvent("on" + type, fn);
if (isNaN(el["cu" + type])) {
// 自定義屬性
el["cu" + type] = 0;
}
var fnEv = function(event) {
if (event.propertyName == "cu" + type) { fn.call(el); }
};
el.attachEvent("onpropertychange", fnEv);
if (!el["ev" + type]) {
el["ev" + type] = [fnEv];
} else {
el["ev" + type].push(fnEv);
}
}
return this;
},
fireEvent: function(type) {
var el = this.el;
if (typeof type === "string") {
if (document.dispatchEvent) {
if (el["ev" + type]) {
el.dispatchEvent(el["ev" + type]);
}
} else if (document.attachEvent) {
el["cu" + type]++;
}
}
return this;
},
removeEvent: function(type, fn, capture) {
var el = this.el;
if (window.removeEventListener) {
el.removeEventListener(type, fn, capture || false);
} else if (document.attachEvent) {
el.detachEvent("on" + type, fn);
var arrEv = el["ev" + type];
if (arrEv instanceof Array) {
for (var i=0; i<arrEv.length; i+=1) {
el.detachEvent("onpropertychange", arrEv[i]);
}
}
}
return this;
}
};
$(elImage) .addEvent("click", funClick); .addEvent("alert", funAlert1); .addEvent("alert", funAlert2);
而funClick方法中有等同下面腳本:
$(e.target).fireEvent("alert");
因此,點(diǎn)擊圖片,才會(huì)出現(xiàn)三個(gè)彈出框:用戶點(diǎn)擊圖片 → 執(zhí)行funClick → 第一個(gè)彈框 → 執(zhí)行fireEvent → 觸發(fā)自定義"alert"事件 → 連續(xù)兩個(gè)"alert"事件彈框
當(dāng)點(diǎn)擊圖片下面的按鈕清除掉自定義"alert"事件后,再點(diǎn)擊圖片就只有一個(gè)彈出