如何實(shí)現(xiàn)以下代碼
window.jQuery = ???
window.$ = jQuery
var $div = $('div')
$div.addClass('red') // 可將所有 div 的 class 添加一個(gè) red
$div.setText('hi') // 可將所有 div 的 textContent 變?yōu)?hi
1俗冻、此函數(shù)接受一個(gè)參數(shù)梨水,這個(gè)參數(shù)可能是node節(jié)點(diǎn)或者是選擇器
window.jQuery = function (nodeOrSelector){}
2乏矾、判斷參數(shù)nodeOrSelector是字符串還是一個(gè)節(jié)點(diǎn),如果是字符串润匙,找到對(duì)應(yīng)的所有元素诗眨,放到偽數(shù)組nodes里面;如果是節(jié)點(diǎn)孕讳,把節(jié)點(diǎn)放到偽數(shù)組nodes里面匠楚,return nodes,封裝成一個(gè)偽數(shù)組nodes
window.jQuery = function (nodeOrSelector){
let nodes
if(typeof nodeOrSelector === 'string'){
nodes = document.querySelectorAll(nodeOrSelector)
}else if(nodeOrSelector instanceof Node){
nodes = {0: nodeOrSelector, length: 1}
}
return nodes
}
3厂财、在nodes上加上API
nodes.addClass = function(){}
nodes.setText = function(){}
4芋簿、 因nodes不是一個(gè)元素,故需要遍歷nodes
nodes.addClass = function(classes){
for(let i = 0; i < nodes.length; i++){
nodes[i].classList.add(classes)
}
}
nodes.setText = function(text){
for(let i = 0; i < nodes.length; i++){
nodes[i].textContent = text
}
}
5璃饱、完整代碼如下
window.jQuery = function (nodeOrSelector){
let nodes
if(typeof nodeOrSelector === 'string'){
nodes = document.querySelectorAll(nodeOrSelector)
}else if(nodeOrSelector instanceof Node){
nodes = {0: nodeOrSelector, length: 1}
}
nodes.addClass = function(classes){
for(let i = 0; i < nodes.length; i++){
nodes[i].classList.add(classes)
}
}
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')