让前端飞JQuery

自己创造一个jQuery

2018-12-28  本文已影响5人  小7丁

一、在window上自己命名一个空间

  1. 首先写出ul>li*5
  2. window上有一个属性xjjdom,他上面有两个方法getSiblings和addClass
    <ul>
    <li id="item1">选项1</li>
    <li id="item2">选项2</li>
    <li id="item3">选项3</li>
    <li id="item4">选项4</li>
    <li id="item5">选项5</li>
  </ul>
  <script>
    window.xjjdom = {}
    xjjdom.getSiblings = function getSiblings (node) {
      var allChildren = node.parentNode.children
      var array = {
        length: 0
      }
      for (let i = 0; i < allChildren.length; i++) {
        if (allChildren[i] !== node) {
          array[array.length] = allChildren[i]
          array.length += 1
        }
      }
      return array
    }
    var classes = ['a', 'b', 'c']
    xjjdom.addClass =  function addClass (node, classes) {
      classes.forEach(i => node.classList.add(i))
    }
    </script>

然后就可以用下面的方式来调用:

xjjdom.getSiblings(item3)
xjjdom.addClass(item3, classes)

二、能否把节点提前到前面

变成如下的方式:

node.getSiblings()
node.addClass()
  1. 在node.prototype上写方法
Node.prototype.getSiblings = function getSiblings () {
      var allChildren = this.parentNode.children
      var array = {
        length: 0
      }
      for (let i = 0; i < allChildren.length; i++) {
        if (allChildren[i] !== this) {
          array[array.length] = allChildren[i]
          array.length += 1
        }
      }
      return array
    }
    var classes = ['a', 'b', 'c']
    Node.prototype.addClass =  function addClass (classes) {
      classes.forEach(i => this.classList.add(i))
    }
    item3.getSiblings()
    item3.addClass(classes)
  1. 重新写一个新的接口
    Node2里面写一个方法对node进行操作,并且里面有一些属性方法。
    这时候将node2改成jQuery就可以了。
window.Node2 = function (nodeOrSelector) {
      let node
      if (typeof nodeOrSelector === 'string') {
        node = document.querySelector(nodeOrSelector)
      } else {
        node = nodeOrSelector
      }
      return {
        getSiblings: function () {
          var allChildren = node.parentNode.children
          var array = {
            length: 0
          }
          for (let i = 0; i < allChildren.length; i++) {
            if (allChildren[i] !== this) {
              array[array.length] = allChildren[i]
              array.length += 1
            }
          }
          return array
        },
        addClass: function (classes) {
          classes.forEach(i => node.classList.add(i))
        }
      }
    }
    var node2 = Node2(item3)
    node2.getSiblings()
    node2.addClass(['a', 'b', 'c'])

再加一个缩写
window.$ = jQuery

上一篇 下一篇

猜你喜欢

热点阅读