一、需求:
构造一个名叫“ jQuery” 的 库,含有API:
1.addClass():给所选元素添加一个class
2.setText():改变所选元素的文本内容
二、实现步骤:
1.获取元素
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){
let nodes = {
0: nodeOrSelector,
length: 1
}
}
return nodes
}
window.$ = jQuery //设置缩写
2.设置一个名叫“addClass”的API
nodes.addClass = function(value) {
for(let i=0;i<nodes.length;i++){
nodes[i].classList.add(value)
}
}
3.设置一个名叫“setText”的API
nodes.setText = function(text) {
if(text === undefined){ //这里多实现了一个功能,即setText()若不输入参数则为获取nodes里的文本内容
let texts = []
for(let i=0;i<nodes.length;i++){
texts.push(nodes[i].textContent)
}
return texts
}else{
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){
let nodes = {
0: nodeOrSelector,
length: 1
}
}
nodes.addClass = function(value) {
for(let i=0;i<nodes.length;i++){
nodes[i].classList.add(value)
}
}
nodes.setText = function(text) {
if(text === undefined){
let texts = []
for(let i=0;i<nodes.length;i++){
texts.push(nodes[i].textContent)
}
return texts
}else{
for(let i=0;i<nodes.length;i++){
nodes[i].textContent = text
}
}
}
return nodes
}
window.$ = jQuery