实现一个 jQuery 的 API

具体实现细节:

代码链接  http://js.jirengu.com/fetuwefine/3/edit?js

window.jQuery  =  function(nodeOrSelector) {

  let nodes = {}

  if(typeof nodeOrSelector === 'string') {

    let temp = docment.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) {

    if(text === undefined) {

      var texts = []

      for(let i=0;i<nodes.length;i++) {

        texts.push(nodes[i].textContent)

      }

    }else {

      for(let i=0;i<nodes.length;i++) {

        nodes[i].textContent = text

      }

    }

  }

  return nodes

}

window.$ = jQuery


使用方式:

var $div = $('div')

$div.addClass('red') // 可将所有 div 的 class 添加一个 red

$div.setText('hi') // 可将所有 div 的 textContent 变为 hi

我们这一生遇到什么样的人和读什么样的书,就能够定规你将来成为什么样的人!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容