实现一个jQuery的API

栏目: jQuery · 发布时间: 5年前

内容简介:在不使用jQuery函数库的情况下自制一个与jQuery同样原理的API:首先,确认以下两个需求:① jQuery的核心思想就是先选择后处理,jQuery构造函数的参数,主要是CSS选择器。选择一个参数,比如,需求1 是让

在不使用jQuery函数库的情况下自制一个与jQuery同样原理的API:

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

var $div = $('div')

1  $div.addClass('red') // 可将所有 div 的 class 添加一个 red
2  $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。


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Learning Vue.js 2

Learning Vue.js 2

Olga Filipova / Packt Publishing / 2017-1-5 / USD 41.99

About This Book Learn how to propagate DOM changes across the website without writing extensive jQuery callbacks code.Learn how to achieve reactivity and easily compose views with Vue.js and unders......一起来看看 《Learning Vue.js 2》 这本书的介绍吧!

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具