实现一个 jQuery 的 API
2020-07-11 本文已影响0人
bananabacteria
window.jQuery = ???
window.$ = jQuery
var $div = $('div')
$div.addClass('red') // 可将所有 div 的 class 添加一个 red
$div.setText('hi') // 可将所有 div 的 textContent 变为 hi
1.首先接收一个node
或选择器
先声明一个变量nodes
,然后对接收的nodeOrSelector
做一下类型检测,如果是字符串,就去找到对应的nodes
伪数组;如果是单个节点,则返回伪数组
let nodes = {}
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
} else if (nodeOrSelector instanceof Node) {
nodes = {
0: nodeOrSelector,
length: 1
}
}
2.封装成一个伪数组
window.jQuery = function(nodeOrSelector) {
let nodes = {}
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
} else if (nodeOrSelector instanceof Node) {
nodes = {
0: nodeOrSelector,
length: 1
}
}
}
3.在伪数组中添加需要的API
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
}
}
4.送出伪数组
window.jQuery = function(nodeOrSelector) {
let nodes = {}
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
} else if (nodeOrSelector instanceof Node) {
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
}
window.$ = jQuery
var $div = $('div')
$div.addClass(['red'])
$div.setText('hi')