獲取目標(biāo)節(jié)點的兄弟節(jié)點
function getsiblings(node){
var allchildren = node.parentNode.children
var array ={length:0}
for(let i=0;i<allchildren.length;i++){
if(allchildren[i]!==node){
arrary[array.length]=allchildren[i]
arrary.length += 1
}
}
return array
}
1.先獲取該節(jié)點父節(jié)點的所有子標(biāo)簽,裝入allchildren對象
2創(chuàng)建arrary對象
3.遍歷所有父節(jié)點的子標(biāo)簽,把不是目標(biāo)節(jié)點的標(biāo)簽放入arrary對象
4返回偽數(shù)組array
把執(zhí)行一個功能的代碼忿磅,裝在一個函數(shù)對象中
getSibling中arry[arry.length]=allchildren[i]
因為返回的是array對象是偽數(shù)組揭朝,array中的key是array.length確定魔策,一開始array.length=0,遍歷一次后偽數(shù)組的length應(yīng)該增加1路召,所以每一次遍歷結(jié)束前array.length +=1勃刨。
addclass,添加classname
一個節(jié)點添加一個class
node.classList.add('string')
一個節(jié)點添加多個class
var classes=['a','b','c']
classes.forEach((value)=>x.classList.add(value))
一個節(jié)點的多個class即能添加又能刪除
function addclass(classes){
if(let key in classes){
var value=classes[key]
var methodName =value?add:remove
node.classList[methodName](key)
}
}
命名空間
addclass對一個元素添加或刪除多個classname股淡,classes中的名為true時添加入node的classname中身隐,value為flase時從node的classname中移除對應(yīng)的key。
獲取多個元素
返回值需要相同類型唯灵,當(dāng)傳入的參數(shù)(nodeOrSelector)是一個節(jié)點贾铝,也要構(gòu)造一個偽數(shù)組
通過臨時偽數(shù)組temp存放querySelectorAll返回的Nodelist(原型指向Node),再遍歷temp把數(shù)據(jù)一個個放到nodes(對象埠帕,原型指向object.prototype)中
注意函數(shù)結(jié)尾不寫return nodes 垢揩,$div將為undefined
#window.$= jQuery
#var $div=$ ('div')
#$div.addClass('red')
#$div.setText('hi')
代碼思路jquery是一個函數(shù),函數(shù)返回一個對象敛瓷,這個對象有addclass和setText兩種方法叁巨。
window.jQuery =function(nodeOrSelector){
var nodes={}
if(typeof nodeOrSelector==='string'){
let temp=document.querySelectorAll(nodeOrSelector)
for(let i=0;i<temp.length;i++){
nodes[i]=temp[i]
}
node[length]=temp[length]
}else if(nodeOrSelector instanceof node){
nodes={0:nodeOrSelector,length:1}
}
}
nodes.addclass=function(classes){
if(let key in classes){
var value=classes[key]
var methodName =value?'add':'remove'
for(let i = 0;i<nodes.length;i++){
node[i].classList[methodName](key)
}
}
聲明變量key在classes對象中通過三元運算符判斷key的boolean,當(dāng)布爾值是true時呐籽,變量methodName的值為字符串a(chǎn)dd俘种,遍歷
全部的節(jié)點,添加或移除classes的key