window.jQuery = (nodeOrSelector) => {
let o = {}
if (typeof nodeOrSelector === "string") {
let nodes = document.querySelectorAll(nodeOrSelector)
nodes.forEach((node,i) => {
o[i] = node
})
o.length = nodes.length
} else if (nodeOrSelector instanceof Node) {
o = {
0: nodeOrSelector,
length: 1
}
}
o.addClass = (cls) => {
for (let i = 0; i < o.length; i++) {
o[i].classList.add(cls)
}
return o
}
o.setText = (text) => {
for (let i = 0; i < o.length; i++) {
o[i].textContent = text
}
return o
}
return o
}
jquery函数既可以接受节点作为参数,也可接受选择器字符串作为参数,然后创建一个对象o,如果参数是选择器字符串,那么用querySelectorAll返回nodes伪数组,遍历nodes,把它加入o中,同时制定length,如果参数是节点对象,也把它加入o中,同时制定length。然后创建两个api放在o中。
网友评论