简单实现JQuery选择器

本文深入探讨了JQuery库中选择器的使用,通过实例解析了以$为起始的选择器可能遇到的三种基本情况,旨在帮助读者逐步掌握JQuery选择器的运用技巧。

$作为选择器时,可能出现的三种情况

<body>
	<h2>这是一个标题</h2>
	<p>这是一个段落。</p>
	<p>这是另一个段落。</p>
	<button>点我</button>
	
	<script>
		console.log($()) // init {}
		console.log($("em")) 
		/*
		init [prevObject: init(1), context: document, selector: "em"]
		context: document
		length: 0
		prevObject: init [document, context: document]
		selector: "em"
		__proto__: Object(0)
		*/
		console.log($("p"))
		/*
		init(2) [p, p, prevObject: init(1), context: document, selector: "p"]
		0: p
		1: p
		context: document
		length: 2
		prevObject: init [document, context: document]
		selector: "p"
		__proto__: Object(0)
		*/
	</script>
</body>
</html>

一步步来实现吧

function $ (selector) {
  return new $.fn.init(selector)
}

$.fn = {
  init: function (selector) {
		// 选择器为空,返回空对象
    if (!selector) {
      return {}
    }
		// 到这一步,表面选择器不为空,给selecotr属性赋值
    this.selector = selector
		// 用querySelectorAll获取所有匹配的DOM元素
    const domList = document.querySelectorAll(selector);
		// 用Array的push方法将查询结果赋值到this上
    Array.prototype.push.apply(this, domList)
		// 设置结果长度
    this.length = domList.length;
		// 返回this
    return this
  },
  size: function () {
    return this.length
  },
  length: 0,
  selector: "",
}

// 令init的原型指向fn,是的init也能使用fn中的属性
$.fn.init.prototype = $.fn

// Array.prototype的实现
function ArrayPush () {
  var n = this.length;
  var m = arguments.length;
  for (var i = 0; i < m; i++) { // 逐个复制元素
    this[i + n] = arguments[i];
  }
  this.length = n + m; // 修改数组的length
  return this.length;
}

Array.prototype.push = Array.prototype.push 
	? Array.prototype.push
	: ArrayPush
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值