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

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

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

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

  1. 我們先寫一個構造函數(shù),用于接收一個節(jié)點,并判斷傳進來的參數(shù)是字符串還是節(jié)點。
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. 我們給這個構造函數(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
  
        }
    }

最終,我們的構造函數(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
}

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

相關閱讀更多精彩內容

  • 問題如下 整體思路如下 我們考慮構造出一個新的函數(shù),返回一個新的對象,該對象包含addClass和setText兩...
    ttcs1991閱讀 223評論 0 0
  • 一、樣式篇 第1章 初識jQuery (1)環(huán)境搭建 進入官方網(wǎng)站獲取最新的版本 http://jquery.co...
    凜0_0閱讀 3,684評論 0 44
  • (2016-04-29-Fri 16:18:37) 激活想法內事項的統(tǒng)計值
    菜五閱讀 327評論 0 0
  • 是文章里的劇情劇情,還是生活里的劇情劇情,那個更劇情!
    格生花閱讀 214評論 0 0
  • 暑假期間,我好像患上了無限拖延癥,這一個月里就干了三件事情,追劇睡覺打榮耀。給自己制定的暑假任務一件也沒有完成。隨...
    奈奈日記閱讀 1,177評論 4 3

友情鏈接更多精彩內容