动力节点首页 全国咨询热线:400-8080-105

绑定手机号,登录
手机号

验证码

微信登录
手机号登录
手机号

验证码

微信登录与注册
微信扫码登录与注册

扫码关注微信公众号完成登录与注册
手机号登录
首页 > 文章

源码解析jQuery的API实现

05-07 17:37 514浏览
举报 T字号
  • 大字
  • 中字
  • 小字

API(Application Programming Interface,应用程序接口)是一些预先定义的接口(如函数、HTTP接口),或指软件系统不同组成部分衔接的约定。用来提供应用程序与开发人员基于某软件或硬件得以访问的一组例程,而又无需访问源码,或理解内部工作机制的细节。在不使用jQuery函数库的情况下自制一个与jQuery同样原理的API:

首先,确认以下两个需求:

 var $div = $('div')

  $div.addClass('red') // 可将所有 div 的 class 添加一个 red
  $div.setText('hi') // 可将所有 div 的 textContent 变为 hi
jQuery本质上就是一个构造函数,我们需要给它输入参数,就可以返回对应参数的jQuery实例。

window.jQuery=function (){}

 jQuery的核心思想就是先选择后处理,jQuery构造函数的参数,主要是CSS选择器。选择一个参数,比如,需求1是让

的class='red', 其中'div'就是要传入的参数。

window.jQuery=function (nodeOrSelector){
  var nodes={}
  let temp=document.querySelectorAll(nodeOrSelector)
  for(let i=0;i<temp.length;i++){
    nodes[i]=temp[i]
  }
  nodes.length=temp.length
  return nodes
}

使用document.querySelectorAll, 因为它遵循的是css选择器的规则,可以帮助我们获取一个或者多个元素节点,用它确定选中参数的结果,在html文档中会获取到多个结果,这个结果集是一个伪数组,遍历这个伪数组,将遍历的结果存放在nodes对象中。

window.jQuery=function (nodeOrSelector){
  var nodes={}
  let temp=document.querySelectorAll(nodeOrSelector)
  for(let i=0;i<temp.length;i++){
    nodes[i]=temp[i]
  }
  nodes.length=temp.length
  nodes.addClass=function (className) {
    for(i=0;i<nodes.length;i++){
      nodes[i].classList.add(className)
    }
}
  return nodes
}

获取到这个nodes对象之后,通过nodes创建一个构造函数,这个函数中的className,就是在window.jQuery使用addClass这个属性时要输入的参数。在这个函数内部创建一个for循环,遍历nodes,每一轮给nodes中对应的节点添加一个className。

就可以实现 需求1了。

window.jQuery=function (nodeOrSelector){
   var nodes={}
   let temp=document.querySelectorAll(nodeOrSelector)
   for(let i=0;i<temp.length;i++){
    nodes[i]=temp[i]
   }
   nodes.length=temp.length
   nodes.addClass=function (className) {
    for(i=0;i<nodes.length;i++){
      nodes[i].classList.add(className)
    }
 }
 nodes.setText=function (text){
  for(i=0;i<nodes.length;i++){
    nodes[i].textContent=text
  }
 }
   return nodes
}

window.$ = jQuery 与需求1 同样的步骤,nodes.setText接受一个参数text,在这个函数内部创建一个for循环,遍历nodes每一轮给nodes中对应的节点添加一个text。

这样两个API就可以实现这两个需求了。它们可以同时给1个或多个元素节点,添加class和textContent。

本文给出的源码都可以在动力节点在线的视频课程中找到对应的部分,想要深入学习的小伙伴可以作为参考,对照找出自己的代码错误。

0人推荐
共同学习,写下你的评论
0条评论
代码小兵988
程序员代码小兵988

67篇文章贡献228982字

相关课程 更多>

作者相关文章更多>

推荐相关文章更多>

JavaWeb的3大组件

代码小兵49806-11 15:28

全面解析Cookie技术

代码小兵49806-11 15:51

浅谈JavaWeb架构演变

代码小兵49806-11 16:22

探讨Web开发中的Session存储与管理

代码小兵51603-29 17:28

JavaScript基础知识

 暴风城-小飞04-06 20:49

发评论

举报

0/150

取消