手写jQuery源码

功能的实现只是机械地调用,框架的编写才是代码的升华

// 避免变量的全局污染
(function(){
    
    
	/* jQuery 构造函数 */
	function jQuery(selector){
    
    
		return new jQuery.fn.init(selector);
		// 返回 init 构造函数创造的实例
	}
	// 原型起个别名
	jQuery.fn = jQuery.prototype;
	
	/* init 初始化方法 */
	jQuery.fn.init = function(selector){
    
    
		if(typeof selector == 'object'){
    
      
			this[0] = selector;
			this.length = 1; 
			// 如果传入的是对象,就把对象当this里面的元素
		}else if(typeof selector == 'function'){
    
     //当selector是函数时候 执行ready方法
			jQuery.fn.ready(selector);
			
		}else{
    
    
			var elems = document.querySelectorAll(selector);
			// 选择到所有的元素
			for(var i=0;i<elems.length;i++){
    
    
				this[i] = elems[i];
			}
			//  变量把选择到的对象挂载到实例上
			
			this.length = elems.length;
			// 设置长度
			return this; //返回 init创造的实例
		}
	}
	
	
	/* dom操作方法 */
	/* each 遍历方法:变量this指向回调函数fn */
	jQuery.fn.each = function(fn){
    
    
		for(var i=0;i<this.length;i++){
    
    
			fn(this[i]);
		}
		return this;
	}
	/* on方法 绑定事件 */
	jQuery.fn.on=function(type,fn){
    
    
		this.each(function(elem){
    
    
			elem.addEventListener(type,fn);
		})
		return this;
	}
	/* toggleClass方法 */
	jQuery.fn.toggleClass=function(name){
    
    
		this.each(function(elem){
    
    
			elem.classList.toggle(name)
		})
		return this;
	}
	jQuery.fn.toggle=function(name){
    
    
		this.each(function(elem){
    
    
			var display = document.defaultView.getComputedStyle(elem,null).display;
			//            文档.默认视图。获取电脑计算的样式(元素,null)
			// 获取浏览器计算过后元素的css属性
			if(display!='none'){
    
     //如果得到display值不是none
				elem.oldview = display; //用oldview 属性记录下
				elem.style.display = 'none'; //隐藏
				
			}else{
    
    
				elem.style.display = elem.oldview||'block';
				// 否则 显示
			}
		})
		return this;
	}
	
	/* 实现ready方法 */
	jQuery.fn.ready = function(callback){
    
    
		if(jQuery.isReady){
    
    
			callback();
		}else{
    
    
			 setTimeout(()=>{
    
    
				 jQuery.fn.ready(callback);
			 },10)
		}
		// 如果jquery 准备好了执行 callback
	}
	document.addEventListener("DOMContentLoaded",e=>jQuery.isReady=true);
	// 文档加载完毕设置jQuery的isReady为true
	
	
	jQuery.fn.init.prototype = jQuery.prototype;
	// 重新指向prototype;(为了让实例拥有jQuery prototype上面的公用方法)
	// 全局挂载
	window.$ = window.jQuery = jQuery;
	
})()
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>jquery</title>
		<script src="js/jquery-5.0.js"></script>
		<style>
			.active{
    
    color:red;}
		</style>
	</head>
	<body>
		<button>切换</button>
		<h1> 我爱<span>我的</span>祖国</h1>
		<p>我喜欢jquery</p>
		<p>我爱vue</p>
		<script>
			// console.log($);
			// console.log(jQuery);
			//  $("p").on("click",function(){
    
    
			// 	  $(this).toggleClass("active");
			//  })
			 
			//  $("button").on("click",function(){
    
    
			// 	 $("span").toggle();
			//  })
			$(function(){
    
    
				// alert("文档加载完毕")
				console.log("文档加载完毕")
			})
			 
		</script>
	</body>
</html>

猜你喜欢

转载自blog.csdn.net/qq_47008195/article/details/108672913