實(shí)現(xiàn)一個簡單的 jQuery 的 API

對于網(wǎng)頁開發(fā)者來說,學(xué)會jQuery是必要的。

jQuery的基本設(shè)計思想和主要用法,就是"選擇某個網(wǎng)頁元素,然后對其進(jìn)行某種操作"。這是它區(qū)別于其他Javascript庫的根本特點(diǎn)。

下面,我們自己寫一個構(gòu)造函數(shù),接收一個節(jié)點(diǎn),返回一個新的節(jié)點(diǎn)對象,同時我們可以使用新節(jié)點(diǎn)的API去做一些事情。

  1. 我們先寫一個構(gòu)造函數(shù),用于接收一個節(jié)點(diǎn),并判斷傳進(jìn)來的參數(shù)是字符串還是節(jié)點(diǎn)。
window.jQuery = function(nodeOrSelector){
 
let nodes = {}
  if(typeof nodeOrSelector === 'string'){
    let temp = document.querySelectorAll(nodeOrSelector)//偽數(shù)組
    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
    }
  }
return nodes
}
  1. 我們給這個構(gòu)造函數(shù)添加兩個屬性:addClass(className) 和 setText(text)
nodes.addClass = function(className){
      
        for(let i=0;i<nodes.length; i++){
          nodes[i].classList.add(className)
  
        }
    
    }
 nodes.setText = function(text){
      for(let i=0;i<nodes.length; i++){
          nodes[i].textContent = text
  
        }
    }

最終,我們的構(gòu)造函數(shù)如下:

window.jQuery = function(nodeOrSelector){
 
let nodes = {}
  if(typeof nodeOrSelector === 'string'){
    let temp = document.querySelectorAll(nodeOrSelector)//偽數(shù)組
    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
    }
  }

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

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

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

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