-
Notifications
You must be signed in to change notification settings - Fork 0
/
jqueryDemo.html
77 lines (70 loc) · 1.62 KB
/
jqueryDemo.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
66
67
68
69
70
71
72
73
74
75
76
77
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<input type="button" id='btn' value="点击我">
<script>
// 模拟jquery 底层链式编程
var a = 10;
(function(window,undefined){
function _$(arguments) {
var idselect = /#\w+/;
this.dom;
if(idselect.test(arguments[0])) {
this.dom = document.getElementById(arguments[0].substring(1));
}else {
throw new Error('arguments is error!');
}
}
Function.prototype.method = function(methodName,fn) {
// 这个this 指向_$(谁调用就指向谁)
this.prototype[methodName] = fn;
return this;
}
// 添加公共方法
_$.prototype = {
constructor:_$,
addEvent:function(type,fn) {
alert('addEvent');
if(window.addEventListener){
this.dom.addEventListener(type,fn);
}else if(window.attachEventListener) {
this.dom.attachEvent('on'+type,fn);
}
return this;
},
setStyle:function(prop , value) {
debugger;
this.dom.style[prop] = value;
alert('setStyle');
return this;
}
}
window.$ = _$;
_$.onReady = function(fn) {
window.$ = function() {
return new _$(arguments);
}
debugger;
fn();
// 实现链式编程
_$.method('addEvent',function() {
alert("nothing to do");
}).method('setStyle',function() {
});
};
})(window);
$.onReady(function() {
// $("#btn").addEvent().setStyle();
var btn = $("#btn");
alert(btn.dom);
btn.addEvent('click',function() {
alert('我被点击了');
}).setStyle('background','red');
});
</script>
</body>
</html>