简单实现jQuery

jQuery的本质是函数,下面来简单实现一下jQuery中的addClass和text

window.jQuery = function() {
    let nodes = {}
    if(typeof nodeOrSelector === 'string') {
        nodes = document.querySelectorAll(nodeOrSelector)
    }else if(nodeOrSelector instanceof Node) {
        nodes = {0: nodeOrSelector, length: 1}
    } else if(nodeOrSelector instanceof NodeList) {
        for(let i in nodeOrSelector) {
            if(nodeOrSelector.hasOwnProperty(i) )
            nodes[i] = nodeOrSelector[i]
        }
        nodes.length = nodeOrSelector.length
    }

    nodes.addClass = function(classes) {
        for(let i = 0; i < nodes.length; i++) {
            let methodName = ''
            for(let key in classes) {
                methodName = classes[key] ? 'add' : 'remove'
                nodes[i].classList[methodName](key)
            }
        }
    }

   nodes.text = 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 < this.length; i++) {
               nodes[i].textContent = text
           }
       }
   }

   return nodes
}

window.$ = jQuery

调用:

$('div').addClass('a').text('Hello World')

简单来说,jQuery是输入参数为字符串(css选择器),Node对象或NodeList对象,输出一个可以操纵输入参数对应的DOM节点对象的函数

上述代码涉及到的主要知识点有:
1. 闭包
如nodes变量和addClass函数就构成一个闭包,可以通过addClass函数访问到局部变量nodes
2. ===
完全相等,建议用来替代所有的‘==’
3. typeof 和 instanceof
typeof 用来判断基本数据类型,instanceof用来判断复杂数据类型(对象)
4. 获取自身对象的可枚举属性
for( i in obj) {
if(obj.hasOwnProperty(i)) {
}
}

猜你喜欢

转载自blog.csdn.net/m0_38102188/article/details/81222139