实现一个简单的 jQuery 的 API(摘录)

对于网页开发者来说,学会jQuery是必要的。

jQuery的基本设计思想和主要用法,就是"选择某个网页元素,然后对其进行某种操作"。这是它区别于其他Javascript库的根本特点。

下面,我们自己写一个构造函数,接收一个节点,返回一个新的节点对象,同时我们可以使用新节点的API去做一些事情。

1、我们先写一个构造函数,用于接收一个节点,并判断传进来的参数是字符串还是节点。

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
    }
  }
return nodes
}

2.我们给这个构造函数添加两个属性:addClass(className) 和 setText(text)

nodes.addClass = function(className){
      
        for(let i=0;i<nodes.length; i++){
          nodes[i].classList.add(className)
  
        }
    
    }
 nodes.setText = function(text){
      for(let i=0;i<nodes.length; i++){
          nodes[i].textContent = text
  
        }
    }

最终,我们的构造函数如下:

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(className){
      
        for(let i=0;i<nodes.length; i++){
          nodes[i].classList.add(className)
  
        }
    
    }
    
    nodes.setText = function(text){
      for(let i=0;i<nodes.length; i++){
          nodes[i].textContent = text
  
        }
    }
    
  return nodes
}

作者:jirengu_li
链接:https://www.jianshu.com/p/67264cbca3f3

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

推荐阅读更多精彩内容

  • jQuery的基本设计思想和主要用法,就是"选择某个网页元素,然后对其进行某种操作"。使用jQuery的第一步,往...
    遠_阅读 318评论 0 0
  • 一、样式篇 第1章 初识jQuery (1)环境搭建 进入官方网站获取最新的版本 http://jquery.co...
    凛0_0阅读 3,531评论 0 44
  • 对于网页开发者来说,学会jQuery是必要的。 jQuery的基本设计思想和主要用法,就是"选择某个网页元素,然后...
    li_liu阅读 256评论 0 0
  • 第一部分 HTML&CSS整理答案 1. 什么是HTML5? 答:HTML5是最新的HTML标准。 注意:讲述HT...
    kismetajun阅读 27,935评论 1 45
  • 阔别两年,我又回到香槟了。根据谷歌的数据,我从一个2400百万人口的大城市来到了一个只有8万人口的地方。 比起前段...
    夏及0412阅读 414评论 0 2