- 自己最近在學(xué)習(xí)一些js的插件的寫法讥耗,那么當(dāng)然就繞不開jquery有勾,于是自己就學(xué)習(xí)中遇到的一些問題做些總結(jié)和記錄
- 自己也是在學(xué)習(xí)過程中,有問題請(qǐng)各位指出葛账,希望大伙能多多支持柠衅,給給star,點(diǎn)點(diǎn)贊唄籍琳,github地址
init方法
先看看之前寫的代碼
var Ye = function(selector){
return Ye.prototype.init(selector);
}
Ye.prototype = {
//....
init:function(selector){
}
//....
}
所以我們要在init中獲取傳進(jìn)來的selector,來構(gòu)造對(duì)象菲宴。在JQ實(shí)際的源碼中,這部分是很復(fù)雜的趋急,要根據(jù)傳進(jìn)來的selector來做不同的處理喝峦,分為下面幾種情況。
- selector為無意義的值呜达,如false,undefined,空字符串谣蠢,null等,這時(shí)候我們就直接返回this,這里的this為一個(gè)空的Ye對(duì)象,length為0.
- selector是一個(gè)DOM元素眉踱,我們只需將其封裝為JQ對(duì)象即可
- 參數(shù)selector為body字符串
- 參數(shù)selector為其他字符串挤忙,這里要分幾種情況
- 是單獨(dú)標(biāo)簽,如$("<div>")谈喳,這就需要用
document.createElement()
來創(chuàng)建DOM册烈,然后封裝成JQ對(duì)象返回 - 是一段復(fù)雜的HTML代碼,如$("<div id="haha"><div id="hehe"></div></div>")婿禽,這個(gè)我們可以利用利用innerHTML來創(chuàng)建個(gè)DOM赏僧,實(shí)際JQ中的方法更加復(fù)雜
- 參數(shù)selector為"#id",直接調(diào)用
document.getElementById()
來查找DOM - 參數(shù)selector為選擇器表達(dá)式扭倾,如:$(".test")
- 參數(shù)selector是一個(gè)函數(shù)淀零,如$(function),我們這時(shí)候應(yīng)該把它當(dāng)成一個(gè)ready事件來處理
- 參數(shù)selector是一個(gè)JQ對(duì)象
- 參數(shù)selector是任意其他值
因?yàn)橛行┣闆r比較少見膛壹,所以我們自己寫的話就不考慮那么多驾中,我寫下1,2模聋,4哀卫,5幾種情況,其他的大家也可以去嘗試撬槽,遇到問題可以交流哈
自己寫
{
init:function(selector){
//1.無意義此改,返回空J(rèn)Q
if(!selector) return this;
//2.如果有nodeType屬性,則認(rèn)為是DOM
if(selector.nodeType){
this[0] = selector;
this.length = 1;
return this;
}
//4.字符串
var elm;
if(typeof selector === "string"){
//首字符為#,且無空格
if(selector.chatAt(0) == "#" !selector.match('\\s')){
elm = document.getElementById(selector);
this[0] = elm;
this.length = 1;
this.selector = selector;
return this;
}else{
elm = document.querySelectorAll(selector);
for(var i = 0; i < elm.length; i++){
this[i] = elm[i];
}
this.length = elm.length;
this.selector = selector;
return this;
}
}
//5.給ready調(diào)用侄柔,后續(xù)會(huì)寫ready()
if(typeof selector == 'function'){
Ye.ready(selector);
return;
}
}
}