-
Notifications
You must be signed in to change notification settings - Fork 59
/
Copy path01、场景1-解决重复性的分支判断.html
65 lines (63 loc) · 1.81 KB
/
01、场景1-解决重复性的分支判断.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<button id="click">click</button>
<script>
let A = {};
A.on = function (dom, type, fn) {
if (dom.addEventListener) {
dom.addEventListener(type, fn, false);
} else if (dom.attachEvent) {
dom.attachEvent('on' + type, fn);
} else {
dom['on' + type] = fn;
}
};
/*
* 上面的代码存在的问题, 每次添加事件都要走一遍能力检测。
* 解决办法之一, 对document能力检测, 通过闭包在页面加载时执行, 达到重写A.on的目的
* */
A.on2 = function (dom, type, fn) {
if (document.addEventListener) {
return function (dom, type, fn) {
dom.addEventListener(type, fn, false);
}
} else if (document.attachEvent) {
return function (dom, type, fn) {
dom.attachEvent('on' + type, fn);
}
} else {
return function (dom, type, fn) {
dom['on' + type] = fn;
}
}
}();
/*
* 解决办法之二: 惰性执行
* */
A.on3 = function (dom, type, fn) {
if (document.addEventListener) {
A.on3 = function (dom, type, fn) {
dom.addEventListener(type, fn, false);
}
} else if (document.attachEvent) {
A.on3 = function (dom, type, fn) {
dom.attachEvent('on' + type, fn);
}
} else {
A.on3 = function (dom, type, fn) {
dom['on' + type] = fn;
}
}
A.on3(dom, type, fn);
};
A.on3(document.getElementById('click'), 'click', function () {
console.log(11)
})
</script>
</body>
</html>