實(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
}

2.我們給這個構(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
}

作者:jirengu_li
鏈接:http://m.itdecent.cn/p/67264cbca3f3

?著作權(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)容

  • jQuery的基本設(shè)計思想和主要用法,就是"選擇某個網(wǎng)頁元素,然后對其進(jìn)行某種操作"。使用jQuery的第一步,往...
    遠(yuǎn)_閱讀 358評論 0 0
  • 一、樣式篇 第1章 初識jQuery (1)環(huán)境搭建 進(jìn)入官方網(wǎng)站獲取最新的版本 http://jquery.co...
    凜0_0閱讀 3,684評論 0 44
  • 對于網(wǎng)頁開發(fā)者來說,學(xué)會jQuery是必要的。 jQuery的基本設(shè)計思想和主要用法,就是"選擇某個網(wǎng)頁元素,然后...
    li_liu閱讀 269評論 0 0
  • 第一部分 HTML&CSS整理答案 1. 什么是HTML5? 答:HTML5是最新的HTML標(biāo)準(zhǔn)。 注意:講述HT...
    kismetajun閱讀 28,888評論 1 45
  • 闊別兩年,我又回到香檳了。根據(jù)谷歌的數(shù)據(jù),我從一個2400百萬人口的大城市來到了一個只有8萬人口的地方。 比起前段...
    夏及0412閱讀 503評論 0 2

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