實(shí)現(xiàn)JQuery之API
1.需求分析
window.jQuery = ???
window.div =
div.addClass('red') // 可將所有 div 的 class 添加一個(gè) red
$div.setText('hi') // 可將所有 div 的 textContent 變?yōu)?hi
2.思路分析
思路:
參數(shù)判斷函數(shù)滚局,找到節(jié)點(diǎn)瞭空,判斷參數(shù)形式
addClass函數(shù)編寫楼雹,實(shí)現(xiàn)查找節(jié)點(diǎn)并添加樣式
setText 函數(shù)編寫玻粪,實(shí)現(xiàn)查找節(jié)點(diǎn)并設(shè)置內(nèi)容
將以上函數(shù)封裝
3.具體方法
3.1 findNodesOrSelector 函數(shù)畦贸,尋找節(jié)點(diǎn)
如果typeof nodeOrSelector是string,那么 作為選擇器,我們就用document.querySelectorAll來獲取所有的元素,返回一個(gè)偽數(shù)組,然后遍歷這個(gè)數(shù)組把每個(gè)value放到nodes里.
如果nodeOrSelector instanceof 是node 那么將nodeOrSelector放到nodes里作為nodes[0]
function findNodesOrSelector(nodeOrSelector){
let nodes ={}
//判斷傳進(jìn)來的參數(shù)是否為 節(jié)點(diǎn)還是字符串
if(typeof nodeOrSelector ==='string' ){ //當(dāng)傳入得到參數(shù)為字符串
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){ //當(dāng)傳入得到參數(shù)為節(jié)點(diǎn)時(shí)
nodes = {
0:nodeOrSelector,
length:1
}
}
return nodes
}
3.2 addClass 函數(shù)編寫,實(shí)現(xiàn)查找節(jié)點(diǎn)并添加樣式
因?yàn)榻o找到的節(jié)點(diǎn)添加樣式,所以要傳入一個(gè)參數(shù);
同時(shí)取募,對已經(jīng)找到的節(jié)點(diǎn)一般情況下不是只有一個(gè),那么我們添加樣式的時(shí)候也是不止給一個(gè)節(jié)點(diǎn)添加樣式蟆技,因此玩敏,需要對每個(gè)節(jié)點(diǎn)分別添加,就要依次對節(jié)點(diǎn)進(jìn)行遍歷质礼。
function addClass(classes){
classes.forEach((value)=>{ //使用箭頭函數(shù)旺聚,第一個(gè)參數(shù)是this即classes
for(let i=0;i<nodes.length;i++){
nodes[i].addClassList.add(value)
}
})
}
3.3 setText 函數(shù)編寫,實(shí)現(xiàn)查找節(jié)點(diǎn)并設(shè)置內(nèi)容
和上面的方法一樣眶蕉,先找到需要改變的節(jié)點(diǎn)砰粹,對它依次遍歷后再設(shè)置其內(nèi)容
同時(shí),傳入一個(gè)參數(shù)造挽,即需要改變之后的參數(shù)
function setText(text){
for(let i=0;i<nodes.length;i++){
nodes[i].textContext = text
}
}
4.封裝
window.jQuery = function(nodeOrSelector){
let nodes={}
//判斷傳進(jìn)來的參數(shù)是否為 節(jié)點(diǎn)還是字符串
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){ //當(dāng)傳入得到參數(shù)為節(jié)點(diǎn)
nodes = {
0:nodeOrSelector,
length:1
}
}
?
nodes.addClass = function (classes){
classes.forEach((value)=>{
for(let i=0;i < nodes.length;i++){
nodes[i].classList.add(value)
}
})
}
?
nodes.setText = function(text){
for(let i =0;i<nodes.length;i++){
nodes[i].textContent = text
}
}
?
return nodes
}