-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathquery.js
73 lines (65 loc) · 1.96 KB
/
query.js
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
/**
* Created by tanjiasheng on 2017/5/4.
*/
import _t from "./tools";
function Query(selector) {
this.el = {};
_t.isString(selector) && (this.el = document.querySelectorAll(selector));
_t.isElement(selector) && (this.el = selector);
}
Query.prototype = {
constructor: Query,
val(val) {
if ($.isVoid(val)) {
return this.el[0] && (this.el[0].value || '');
}
$.each(this.el, (e) => {
e.value = val;
});
return this;
},
attr(key, value) {
if ($.isVoid(value)) {
return this.el[0] && (this.el[0].getAttribute(key) || '');
}
$.each(this.el, (e) => {
e.setAttribute(key, value);
});
return this;
},
getEl() {
return $.isArrayLike(this.el) ? this.el : null;
},
addClass(str) {
if ($.isArrayLike(this.el)) {
$.each(this.el, (e) => {
if (!$(e).hasClass(str)) {
e.className += e.className.length > 0 ? ` ${str}` : str;
}
});
} else /*if($.isElement(this.el))*/ {
this.el.className += this.el.className.length > 0 ? ` ${str}` : str;
}
},
removeClass(str) {
if ($.isArrayLike(this.el)) {
$.each(this.el, (e) => {
if ($(e).hasClass(str)) {
e.className.indexOf(str) == 0 ? e.className = e.className.replace(str, '') : e.className = e.className.replace(` ${str}`, '');
}
});
} else /*if($.isElement(this.el))*/ {
this.el.className.indexOf(str) == 0 ? this.el.className = this.el.className.replace(str, '') : this.el.className = this.el.className.replace(` ${str}`, '');
}
},
hasClass(str) {
if ($.isElement(this.el)) {
return this.el.className.indexOf(str) > -1
}
}
};
function $(selector) {
return new Query(selector);
}
_t.extend($, _t);
export default $;