實現(xiàn)jQuery的API

1. jQuery函數(shù)結(jié)構(gòu)

jQuery函數(shù)要方便與輸入一個選擇器參數(shù)或則節(jié)點正確返回一個偽數(shù)組,便于對其明確執(zhí)行后續(xù)方法,jQuery函數(shù)結(jié)構(gòu)即為自身的hash結(jié)構(gòu),所以實現(xiàn)一個新的jQuery結(jié)構(gòu)函數(shù)可以由如下圖標(biāo)號1所指的選擇器、標(biāo)號2所指的函數(shù)方法、標(biāo)號3所返回的最終轉(zhuǎn)換好的jQuery對象組成,后續(xù)為介紹。

image

2. 實現(xiàn)jQuery的API之選擇器

對于標(biāo)號1部分,對于節(jié)點和選擇器的參數(shù)都可返回所需要的偽數(shù)組對象的index-value以及l(fā)ength-value的hash。

let nodes = {}
  if (typeof nodeOrSelector === 'string'){
    let temp = document.querySelectorAll(nodeOrSelector)
    for (let i = 0;i< temp.length;i++){
      nodes[i] = temp[i]
    }
    nodes.length = temp.length
  }else if(nodeOrSelector instanceof Node){
    nodes={
      0:nodeOrSelector,
      length:1
    }
  }

3. 實現(xiàn)jQuery的API之函數(shù)對象的方法

對于標(biāo)號2部分,添加所需的jQuery函數(shù)方法,如標(biāo)號2.1的addClass()方法,以及標(biāo)號2.2的setText()方法。

nodes.addClass = function(classes){
        [classes].forEach( (value) => {
        for (let i = 0;i < nodes.length;i++) {
        nodes[i].classList.add(value)
        }
      })
  }
  
  nodes.setText = function(text){
    for(let i=0;i<nodes.length;i++){
      nodes[i].textContent = text
    }
  }
  return nodes
}

4. 返回jQuery對象

在標(biāo)號3為最終返回的jQuery對象,該對象包含標(biāo)號1和2的hash,該對象的引用地址將被賦值給window.jQuery。

5. jQuery的API使用

對于window.jQuery的調(diào)用,使用$的標(biāo)識符命名jQuery對象。

window.$ = jQuery

var $div = $('div')//聲明對應(yīng)的jQuery對象
$div.addClass('red')
$div.setText('hi')
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容