# 前言
最近开发了一个简单页面,打算引入高效高性能的jq库,可是回头一想,jq其实还是挺大的。然而时间也足够,我就按照自己的想法写一个轻量型的jq也挺不错的嘛。说干就干,撸起袖子写了3个小时终于拿下。
# 思路
jq的链式调用的核心就是他的函数返回自己,即 return this。根据这个原理,我们采用工厂模式即可,原型链上某些函数返回自己即可。代码如下:
// 自定义可链式调用的选择器
window.$ = function (str, only) {
function f(str) {
if (typeof str === 'string') {
var val = str.slice(1, str.length);
this.dom = null;
var _this = this;
if (str[0] == '.') {
this.dom = document.getElementsByClassName(val);
}
if (str[0] == '#') {
this.dom = [document.getElementById(val)];
}
} else {
this.dom = [str];
}
this.getDom = function () {
return this.dom.length > 1 ? this.dom : this.dom[0];
}
this.on = function (event, cb) {
this.forEach(function (dom) {
dom.addEventListener(event, cb);
})
}
this.parent = function () {
return this.dom.parent;
}
this.addClass = function (s) {
this.forEach(function (dom) {
dom.classList.add(s);
})
return this;
}
this.hasClass = function (s) {
}
this.toggle = function (s) {
this.forEach(function (dom) {
dom.classList.toggle(s);
})
return this;
}
this.rmClass = function (s) {
this.forEach(function (dom) {
dom.classList.remove(s);
})
return this;
}
this.txt = function (s) {
this.forEach(function (dom) {
dom.innerText = s;
})
return this
}
this.val = function (s) {
if (s == undefined) {
return this.dom[0].value
} else {
this.forEach(function (dom) {
dom.value = s;
})
return this;
}
}
this.style = function (s) {
this.forEach(function (dom) {
dom.style = s;
})
return this;
}
this.attr = function (a, b) {
this.forEach(function (dom) {
dom.setAttribute(a, b);
})
return this;
}
this.rmAttr = function (s) {
this.forEach(function (dom) {
dom.removeAttribute(s);
})
return this;
}
this.getAttr = function (s) {
return this.dom[0].getAttribute(s);
}
this.html = function (s) {
this.forEach(function (dom) {
dom.innerHTML = s;
})
return this;
}
this.appendChild = function (dom) {
this.dom[0].appendChild(dom)
}
this.forEach = function (cb) {
for (var ii = 0; ii < this.dom.length; ii++) {
cb(this.dom[ii]);
}
}
return this;
}
return only ? new f(str).getDom() : new f(str);
}
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
代码在这里,献丑了