源码:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<input type="button" value="test1" id="btn1" class="btn">
<input type="button" value="test2" id="btn2" class="btn">
<input type="button" value="test3" id="btn3" class="btn">
<script>
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*/
removeHandler:function(element,type,handler) { /*Chrome*/
if (element.removeEventListener){
element.removeEventListener(type, handler, false);
}else if (element.deattachEvent) { /*IE*/
element.deattachEvent('on' + type, handler);
}else {
element["on" + type] = null;
}
}
};
// 获取元素
var btn=document.getElementsByClassName("btn");
// 事件
var bangding=function(){
alert("你好!")
}
// 给btn添加 bangding 事件
EventUtil.addHandler(btn[0],"click",bangding);
</script>
</body>
</html>
更多咨询:
网友评论