美文网首页
模仿jQuery封装一个函数

模仿jQuery封装一个函数

作者: 易景平 | 来源:发表于2021-01-26 14:51 被阅读0次

    目的:模仿jQuery的使用模式封装一个函数,并增加一个新方法
    基本思路:声明一个函数,该函数接受一个参数并返回一个新对象,该对象有一个属性的值为函数。

    function jDom(selector){
      let currentNode = document.querySelector(selector)
      let jObj = {0:curentNode,length:1}
      jObj.getSiblings = function(){}
      return jObj
    }
    

    P

    新增方法为获取一个元素的所有兄弟元素,使用DOM的API来实现。

    var getSiblings = function(currentNode){
      let allChild = currentNode.parentNode.children
      let siblings = {length:0}
      for(let i = 0;i<allChild.length;i++){
          if(allChild[i] !==currentNode){
              siblings[siblings.length] = allChild[i]
              siblings.length +=1
          }
       }
       return siblings
    }
    

    把这个函数作为匿名函数赋值给jObj的getsiblings属性

    window.$ = jDom
    

    最后可以像jQuery那样操作,获得id为hero的标签的所有兄弟元素。

    $('#hero').getSiblings.call()
    

    相关文章

      网友评论

          本文标题:模仿jQuery封装一个函数

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