-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjquery-mini.js
63 lines (59 loc) · 1.87 KB
/
jquery-mini.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
(function(){
var jq = function(selector){
//selector = "#div1";
return new jq.fn.init(selector);
}
jq.fn = {
init:function(selector){
// ID选择器/标签选择器开发
// 判断是否有"#号"
if(selector.substr(0,1)==='#')
{
// 去除selector的"#号"
var flag = selector.substr(1,selector.length-1);
var elem = document.getElementById(flag);
// this代表jquery实例化出来的对象
// jquery对象 与 dom对象 做合并
this.length = 1;
this[0] = elem;
}else{
var elems = document.getElementsByTagName(selector);
// 遍历elems获得每个dom对象分别存储
// 到jquery实例化出来的对象(this)里边
for(var i=0; i<elems.length; i++){
this[i] = elems[i];
}
this.length = elems.length;
}
},
css:function(k,v){
// this代表调用该方法的当前对象(jquery对象)
// this[0].style[k] = v;
// 遍历当前的jquery对象,为每个具体dom对象设置css样式
for(var i=0; i<this.length; i++){
this[i].style[k] = v;
}
},
attr:function(k,v){
for(var i=0; i<this.length; i++){
this[i].setAttribute(k,v);
}
},
each:function(callback){
// 遍历jquery对象,使得每个dom对象都执行一次callback
for(var i=0; i<this.length; i++){
// this[i]
// callback();
// callback.call(函数内部this的指引,函数形参,形参,形参);
// callback函数随着for循环执行了多次,
// 每次执行的时候内部this都指向“this[i]的dom对象”
callback.call(this[i],i,this[i]);
}
}
}
// 设置init()构造函数通过原型prototype方式继承jq.fn()
// 这样new init()的对象不仅可以方法init内部成员,还可以方法fn的成员
jq.fn.init.prototype = jq.fn;
// 给jquery声明外部使用接口变量
window.$ = jq;
})();