在不使用jQuery函數(shù)庫(kù)的情況下自制一個(gè)與jQuery同樣原理的API:
首先蝙茶,確認(rèn)以下兩個(gè)需求:
var $div = $('div')
1? $div.addClass('red') // 可將所有 div 的 class 添加一個(gè) red
2? $div.setText('hi') // 可將所有 div 的 textContent 變?yōu)?hi
jQuery本質(zhì)上就是一個(gè)構(gòu)造函數(shù)落包,我們需要給它輸入?yún)?shù)录平,就可以返回對(duì)應(yīng)參數(shù)的jQuery實(shí)例乡恕。
window.jQuery=function (){}
(1)
jQuery的核心思想就是先選擇后處理睦番,jQuery構(gòu)造函數(shù)的參數(shù)良拼,主要是CSS選擇器筹淫。選擇一個(gè)參數(shù)想际,比如皱炉,需求1 是讓<div>的class='red', 其中'div'就是要傳入的參數(shù)怀估。
(2)
window.jQuery=function (nodeOrSelector){
? var nodes={}
? let temp=document.querySelectorAll(nodeOrSelector)
? for(let i=0;i<temp.length;i++){
? ? nodes[i]=temp[i]
? }
? nodes.length=temp.length
? return nodes
}
使用document.querySelectorAll, 因?yàn)樗裱氖莄ss選擇器的規(guī)則,可以幫助我們獲取一個(gè)或者多個(gè)元素節(jié)點(diǎn)合搅,用它確定選中參數(shù)的結(jié)果多搀,在html文檔中會(huì)獲取到多個(gè)結(jié)果,這個(gè)結(jié)果集是一個(gè)偽數(shù)組灾部,遍歷這個(gè)偽數(shù)組康铭,將遍歷的結(jié)果存放在nodes對(duì)象中。
(4)
window.jQuery=function (nodeOrSelector){
? var nodes={}
? let temp=document.querySelectorAll(nodeOrSelector)
? for(let i=0;i<temp.length;i++){
? ? nodes[i]=temp[i]
? }
? nodes.length=temp.length
? nodes.addClass=function (className) {
? ? for(i=0;i<nodes.length;i++){
? ? ? nodes[i].classList.add(className)
? ? }
}
? return nodes
}
獲取到這個(gè)nodes對(duì)象之后梳猪,通過nodes創(chuàng)建一個(gè)構(gòu)造函數(shù),這個(gè)函數(shù)中的className麻削,就是在window.jQuery使用addClass這個(gè)屬性時(shí)要輸入的參數(shù)蒸痹。在這個(gè)函數(shù)內(nèi)部創(chuàng)建一個(gè)for循環(huán),遍歷nodes,每一輪給nodes中對(duì)應(yīng)的節(jié)點(diǎn)添加一個(gè)className呛哟。
就可以實(shí)現(xiàn) 需求1了叠荠。
(5)
window.jQuery=function (nodeOrSelector){
? var nodes={}
? let temp=document.querySelectorAll(nodeOrSelector)
? for(let i=0;i<temp.length;i++){
? ? nodes[i]=temp[i]
? }
? nodes.length=temp.length
? nodes.addClass=function (className) {
? ? for(i=0;i<nodes.length;i++){
? ? ? nodes[i].classList.add(className)
? ? }
}
nodes.setText=function (text){
? for(i=0;i<nodes.length;i++){
? ? nodes[i].textContent=text
? }
}
? return nodes
}
window.$ = jQuery
與需求1 同樣的步驟,nodes.setText接受一個(gè)參數(shù)text,在這個(gè)函數(shù)內(nèi)部創(chuàng)建一個(gè)for循環(huán)扫责,遍歷nodes每一輪給nodes中對(duì)應(yīng)的節(jié)點(diǎn)添加一個(gè)text榛鼎。
這樣兩個(gè)API就可以實(shí)現(xiàn)這兩個(gè)需求了。它們可以同時(shí)給1個(gè)或多個(gè)元素節(jié)點(diǎn)鳖孤,添加class和textContent者娱。