实现一个简单的 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
}
  1. 我们给这个构造函数添加两个属性: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
}

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

推荐阅读更多精彩内容

  • 问题如下 整体思路如下 我们考虑构造出一个新的函数,返回一个新的对象,该对象包含addClass和setText两...
    ttcs1991阅读 195评论 0 0
  • 一、样式篇 第1章 初识jQuery (1)环境搭建 进入官方网站获取最新的版本 http://jquery.co...
    凛0_0阅读 3,482评论 0 44
  • (2016-04-29-Fri 16:18:37) 激活想法内事项的统计值
    菜五阅读 307评论 0 0
  • 是文章里的剧情剧情,还是生活里的剧情剧情,那个更剧情!
    格生花阅读 204评论 0 0
  • 暑假期间,我好像患上了无限拖延症,这一个月里就干了三件事情,追剧睡觉打荣耀。给自己制定的暑假任务一件也没有完成。随...
    奈奈日记阅读 1,078评论 4 3