實(shí)現(xiàn)一個(gè) jQuery 的 API

需要實(shí)現(xiàn)的效果:
1.可將所有 div 的 class 添加一個(gè) red
2.可將所有 div 的 textContent 變?yōu)?hi
補(bǔ)全問號(hào)處的代碼

window.jQuery = ???
window.$ = jQuery

var $div = $('div')
$div.addClass('red') 
$div.setText('hi') 

思路如下:
初始化一個(gè)hash對(duì)象
判斷傳入?yún)?shù)為字符串(選擇器)還是節(jié)點(diǎn)
①若為字符串 => 尋找對(duì)應(yīng)節(jié)點(diǎn)=>放入hash
②若為節(jié)點(diǎn)=>直接放入hash

window.jQuery=function(nodeOrSelector){
    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
      //這里用了一個(gè)中間變量temp只是為了讓nodes結(jié)果更純凈,去掉也可以
    }else if(nodeOrSelector instanceof Node){
        nodes={
        0:nodeOrSelector,
        length:1
      }
    }

添加兩個(gè)方法函數(shù)
使用DOM API

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

完整代碼如下:

window.jQuery=function(nodeOrSelector){
    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
      //這里用了一個(gè)中間變量temp只是為了讓nodes結(jié)果更純凈,去掉也可以
    }else if(nodeOrSelector instanceof Node){
        nodes={
        0:nodeOrSelector,
        length:1
      }
    }
    nodes.addClass=function(classes){
       for(let i=0;i<nodes.length;i++){
                nodes[i].classList.add(classes)            
            }
     }          
    nodes.setText=function(text){
      for(let i=0;i<nodes.length;i++){
        nodes[i].textContent=text
      }      
    }
return nodes
}

window.$ = jQuery
var $div = $('div')
$div.addClass('red') 
$div.setText('hi')

優(yōu)化:
代碼中addClass方法一次只允許傳一個(gè)值,若希望傳多個(gè)class,可改為傳數(shù)組,并使用forEach方法;
setText方法傳值后,會(huì)覆蓋掉原本的文本,若希望完善一些,可添加判斷語句

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

nodes.text=function(text){
    if(text===undefined){
        let text=[]
        for(i=0;i<nodes.length;i++){
            text.push(nodes[i].textContent)
        }
        return text
    }else{
        for(let i=0;i<nodes.length;i++){
            nodes[i].textContent=text}
        }
    }
    return nodes
}
$div.addClass(['red','blue']) //添加了兩個(gè)class
$div.text('hi') // 用hi覆蓋原文本
$div.text() // 返回文本
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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