如何自己做一个jQuery
沉沙 2018-07-24 来源 : 阅读 1198 评论 0

摘要:本篇jQuery教程探讨了如何自己做一个jQuery,希望阅读本篇文章以后大家有所收获,帮助大家对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.jQueryvar $div = $('div')  //获取所有div元素

$div.addClass('red')

$div.setText('hi')

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

 

本文由职坐标整理发布,更多相关内容,请关注职坐标WEB前端jQuery频道!

本文由 @沉沙 发布于职坐标。未经许可,禁止转载。
喜欢 | 0 不喜欢 | 0
看完这篇文章有何感觉?已经有0人表态,0%的人喜欢 快给朋友分享吧~
评论(0)
后参与评论

您输入的评论内容中包含违禁敏感词

我知道了

助您圆梦职场 匹配合适岗位
验证码手机号,获得海同独家IT培训资料
选择就业方向:
人工智能物联网
大数据开发/分析
人工智能Python
Java全栈开发
WEB前端+H5

请输入正确的手机号码

请输入正确的验证码

获取验证码

您今天的短信下发次数太多了,明天再试试吧!

提交

我们会在第一时间安排职业规划师联系您!

您也可以联系我们的职业规划师咨询:

小职老师的微信号:z_zhizuobiao
小职老师的微信号:z_zhizuobiao

版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
 沪公网安备 31011502005948号    

©2015 www.zhizuobiao.com All Rights Reserved

208小时内训课程