自己做一个jQuery

什么是jQuery?

jQuery本质只是一个中间层,提供一套统一易用的DOM操作接口。

那么,今天我们就来自己实现一个简易版的jQuery
首先我们来实现选择器

window.jQuery = function(nodeOrSelector){
  let nodes = {}  //统一使用对象
  //首先我们需要判断用户是想获取多个元素节点还是一个
  if(typeof nodeOrSelector === 'string'){
    let temp = document.querySelectorAll(nodeOrSelector)
    //遍历临时对象temp,将他的值放入nodes内,这样我们就能得到一个纯净的对象,而不是querySelectorAll返回的NodeList
    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
    }
  }
  return nodes  //返回nodes
}

接下来我们为nodes添加addClass方法:

  //classes是用户想要添加的class名
 nodes.addClass = function(classes){
    //遍历nodes,为nodes内每一个元素节点添加class
    for(let i=0;i<nodes.length;i++){
      nodes[i].classList.add(classes)
    }
  }

最后我们为nodes添加setText方法:

//text是用户想要添加的文本
nodes.setText = function(text){
    //遍历nodes,为nodes内每一个元素节点的textContent添加text
    for(let i=0;i<nodes.length;i++){
      nodes[i].textContent = text
    }
  }

最后我们再创建一个window对象

window.$ = window.jQuery

下面是完整代码

window.jQuery = function(nodeOrSelector){
  let nodes = {}
  if(typeof nodeOrSelector === 'string'){
    let temp = document.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){
    for(let i=0;i<nodes.length;i++){
      nodes[i].classList.add(classes)
    }
  }
  
  
  nodes.setText = function(text){
    for(let i=0;i<nodes.length;i++){
      nodes[i].textContent = text
    }
  }
  
 return nodes
}

window.$ = window.jQuery
var $div = $('div')  //获取所有div元素
$div.addClass('red')
$div.setText('hi')

ok,这样我们就初步实现了自己的简易版jQuery(以上使用到了闭包)。

猜你喜欢

转载自blog.csdn.net/weixin_34049948/article/details/87433262