$作为选择器时,可能出现的三种情况
<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
本文深入探讨了JQuery库中选择器的使用,通过实例解析了以$为起始的选择器可能遇到的三种基本情况,旨在帮助读者逐步掌握JQuery选择器的运用技巧。
860

被折叠的 条评论
为什么被折叠?



