美文网首页
模仿jQuery实现一个API

模仿jQuery实现一个API

作者: 祈念念念 | 来源:发表于2019-01-03 13:42 被阅读0次

title: 模仿jQuery实现一个API
date: 2018-09-29 16:46:48
tags: [JavaScript]
categories: JavaScript


如何模仿jQuery实现一个API?

jQuery是一个 JavaScript 库,核心理念是 - write less, do more。
其实jQuery就是一个函数,里面封装了很多方法,我们通过这些方法来获取节点(元素)并进行操作,大大方便了我们的编程。

  • 那么关于下面的代码,如何实现类似jQuery提供的api呢?
window.jQuery = ???
window.$ = jQuery

var $div = $('div')
$div.addClass(['red','blue']) // 可将所有 div 的 class 添加 red 和 blue  注意这里是数组的写法
$div.setText('hi') // 可将所有 div 的 textContent 变为 hi
  1. 首先获取对象
window.jQuery = function(nodeOrSelector){
    let nodes = {}  //初始化对象
    //判断用户想获取一个还是多个节点
    if(typeof nodeOrSelector === 'string'){     //多个节点
        let temp = document.querySelectorAll(nodeOrSelector)   // 伪数组
        //遍历临时对象temp,将它的值放入nodes内,得到一个纯净的伪数组,原型链指向Object
        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
        }
    }
    return nodes  //返回nodes
}
  1. 添加addClass方法
nodes.addClass = function(classes){
    // 用户在addClass中输入的是数组所以用forEach
    classes.forEach((value) =>{
        //遍历nodes,为nodes内每一个元素节点添加class
        for(let i = 0 ; i<nodes.length; i++){
            nodes[i] .classList.add(value)
        }
    })
}
  1. 添加setText方法
nodes.setText = function(text){
    //遍历nodes,为nodes内每一个元素节点的textContent添加text
    for(let i=0;i<nodes.length;i++){
        nodes[i].textContent = text
    }
}
  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){
        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','blue']) // 可将所有 div 的 class 添加 red 和 blue
$div.setText('hi') // 可将所有 div 的 textContent 变为 hi

完成,另外以上代码还使用到了JS的闭包。

相关文章

网友评论

      本文标题:模仿jQuery实现一个API

      本文链接:https://www.haomeiwen.com/subject/hdatrqtx.html