美文网首页
实现一个 jQuery 的 API

实现一个 jQuery 的 API

作者: 饥人谷_目子夏 | 来源:发表于2019-03-23 17:31 被阅读0次

    代码

    window.jQuery=function(nodeOrSelector){
      let nodes=[]
      if(nodeOrSelector === 'string'){
        let temp = document.querySelectorAll(nodeSelector)
        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.lenght;i++)
          {
            nodes[i].textContent=text
          }
      }
      return nodes
    }
    

    获取dom节点

    1.要判断传入的是字符串还是节点
    2.最后要封装成一个伪数组

    编写addClass方法

    1.forEach方法遍历传入的参数数组
    2.遍历第一步的伪数组,用dom api给数组中节点添加类
    3.把该方法添加到伪数组中(node.addClass=function...)

    编写setText方法

    1.遍历第一步的伪数组,用dom api提供的textContent更新数组节点的文本
    3.把该方法添加到伪数组中(node.setText=function...)

    注意

    window.$ = jQuery
    var $div = $('div')
    

    用jQ取值并赋值给变量时给变量前面加$

    instanceof

    instanceof运算符用于测试构造函数的prototype属性是否出现在对象的原型链中的任何位置

    • 事例
    function C(){} 
    function D(){} 
    
    var o = new C();
    
    o instanceof C; // true,因为 Object.getPrototypeOf(o) === C.prototype
    
    o instanceof D; // false,因为 D.prototype不在o的原型链上
    

    相关文章

      网友评论

          本文标题:实现一个 jQuery 的 API

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