本文实例为大家分享了js事件处理程序的具体代码,供大家参考,具体内容如下
<div class="jb51code">
<pre class="brush:xhtml;">
<!DOCTYPE html>
<html lang="en">
<
Meta charset="UTF-8">
DOM0级DOM2级
function show() {
alert("btn1");
}
//DOM0级
var btn2 = document.getElementById("btn2");
btn2.onclick = function () {
alert("DOM0级btn2");
};
//DOM2级
function show2() {
alert("DOM2级btn3");
}
var btn3 = document.getElementById("btn3");
// btn3.addEventListener("click",show2,false);
// btn3.removeEventListener("click",false);
//ie事件处理程序
// btn3.attachEvent("onclick",show2);
// btn3.detachEvent("onclick",show2);
//跨浏览器事件处理程序
//能力检测
var eventUtil = {
//
添加具柄;
addHandler:function (element,type,handler) {
if (element.addEventListener){
element.addEventListener(type,handler,false);
}else if(element.attachEvent){
element.attachEvent("on"+type,handler);
}else {
element["on"+type]=handler;
}
},//
删除具柄;
removeHandler:function (element,handler) {
if (element.removeEventListener){
element.removeEventListener(type,false);
}else if(element.detachEvent){
element.detachEvent("on"+type,handler);
}else {
element["on"+type]=null;
}
}
};
eventUtil.addHandler(btn3,"click",show2);
eventUtil.removeHandler(btn3,show2);