-
Notifications
You must be signed in to change notification settings - Fork 2
/
eventListener.html
43 lines (38 loc) · 1.23 KB
/
eventListener.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<html>
<head>
<title>实现JS添加事件,并且this 指向Dom元素,兼容不同浏览器</title>
<script src='command.js'></script>
</head>
<body>
<input type="button" id='bt' value='Click' data-msg='This is a message for button'>
<script>
var obj = document.getElementById('bt');
addEventlistener(obj, 'click', function(e) {
// IE6,7,8 this 指向Windows ,所有不能直接用This,通过Event获取目标元素
e = e || window.event;
var _this = e.srcElement || e.target;
alert(_this.id + ";");
})
function addEventlistener(obj, type, cb) {
if (obj.addEventListener) {
obj.addEventListener(type, cb);
} else {
obj.attachEvent('on' + type, cb);
}
}
function addEvent(elem,type,handler){
if(elem.addEventListener){
elem.addEventlistener(type,handler,false);
}else if(elem.attachEvent){
elem['temp'+type+handler]=handler;
elem[type+handler]=function{
elem['temp'+type+handler].apply(elem);
}
elem.attachEvent('on'+type,elem[type+handler]);
}else{
elem['on'+type]=handler
}
}
</script>
</body>
</html>