首先
要實現(xiàn)的兩個功能addClass和setText
首先蛛砰,我們要對jQuery進行封裝黍衙,首先選中一個dom元素(或是一個選擇器),我們假設這個只傳入一個dom元素琅翻,那么
let nodes={0:nodeOrSelector,length:1}
然后判斷傳入的nodeOrSelector的類型是否為字符串,如果是字符串聂抢,就表示傳入了一個選擇器,那么我們先用一個temp接受這個選擇器能找到的全部元素琳疏,并將temp中的每一個元素都覆蓋到nodes上闸拿,包括length空盼。
window.jQuery=function(nodeOrSelector){
let nodes={0:nodeOrSelector,length:1}
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
}
然后開始寫兩個功能
addClass:addClass的功能是給選中的元素加上我們輸入的效果
nodes.addClass=function(classes){}
先判斷classed是不是字符串新荤,如果是字符串揽趾,先遍歷一邊nodes里的元素苛骨,然后給每個元素添加效果,如果不是字符串智袭,則用forEach(value)將每個效果添加到對應的元素上
nodes.addClass=function(classes){
if(typeof classes==='string'){
for(let i=0;i<nodes.length;i++){
nodes[i].classList.add(classes)}
}else{
for(let i=0;i<nodes.length;i++){
classes.forEach( (value)=>nodes[i].classList.add(value) )
}
}
}
setText:setText功能是給選中的元素加上文本內容掠抬,首先遍歷一邊選中的元素,然后用textContext方法將我們輸入的文本添加至選中的元素中
nodes.setText=function(text){
for(let i=0;i<nodes.length;i++){
nodes[i].textContent=text
}
}
完整代碼:
window.jQuery=function(nodeOrSelector){
let nodes={0:nodeOrSelector,length:1}
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
}
nodes.addClass=function(classes){
if(typeof classes==='string'){
for(let i=0;i<nodes.length;i++){
nodes[i].classList.add(classes)}
}else{
for(let i=0;i<nodes.length;i++){
classes.forEach( (value)=>nodes[i].classList.add(value) )
}
}
}
nodes.setText=function(text){
for(let i=0;i<nodes.length;i++){
nodes[i].textContent=text
}
}
return nodes
}
window.('div')
node2.addClass('red')