具體的思路:
1.封裝一個(gè)函數(shù),傳入節(jié)點(diǎn)或者選擇器字符串氏堤,可以返回偽數(shù)組沙绝,偽數(shù)組中包含獲取到的dom元素
==> 對(duì)函數(shù)的參數(shù)進(jìn)行判斷,并構(gòu)造一個(gè)臨時(shí)對(duì)象鼠锈,將節(jié)點(diǎn)或者遍歷選擇器得到的節(jié)點(diǎn)存入臨時(shí)對(duì)象并返回
2.在這個(gè)返回的對(duì)象上闪檬,可以添加上一下方法操作dom
window.jQuery = function (selectOrNode) {
let nodes = {} //創(chuàng)建一個(gè)空對(duì)象,最后返回這個(gè)對(duì)象
if (typeof selectOrNode === 'string') { //判斷傳入的是選擇器還是Node節(jié)點(diǎn)
let items = document.querySelectorAll(selectOrNode)
for (let i = 0; i < items.length; i++) {
nodes[i] = items[i]
}
nodes.length = items.length //添加長(zhǎng)度標(biāo)記购笆,方便后邊使用
} else if (selectOrNode instanceof Node) {
nodes.length = 1
nodes[0] = selectOrNode
}
nodes.addClass = function (classes) {
for (let i in classes) {
let name = classes[i] ? "add" : "remove"
for (let l = 0; l < nodes.length; l++) {
nodes[l].classList[name](i)
}
}
}
nodes.text=function(text){
if(text === undefined){
var texts=[]
for(let i=0;i<nodes.length;i++){
console.log(nodes[i])
texts.push(nodes[i].textContent)
}
console.log(texts)
return text
}else {
for(let i=0;i<nodes.length;i++){
nodes[i].textContent = text
}
}
}
return nodes
}
let classes = {
blue: true,
a: false,
c: true
}
let node2 = window.jQuery("ul>li")
node2.addClass.call(node2, classes)
node2.text.call(node2,"11")