我知道jQuery
函数$("selector")
返回一个对象。
var divTest = $(".test"); // returns object
Array.isArray(divTest); // false
typeof divTest; // "object"
使用这个由 jQuery
函数包装的对象,我们可以使用 jQuery
的 API .
我无法理解的一点是我们如何像在数组中那样使用jQuery
对象中的索引访问本机 DOM 元素。
<div class="test first"></div>
<div class="test second"></div>
<div class="test third"></div>
//...
var divTest = $(".test");
console.log(divTest[0]); // <div class="test first"></div>
console.log(divTest[1]); // <div class="test second"></div>
console.log(divTest[2]); // <div class="test third"></div>
我打开了未压缩的jQuery
源文件。我认为这个问题与以下方法有关。
该方法返回jQuery.fn.init
jQuery.makeArray(selector, this)
。 makeArray
是从jQuery
扩展的。
有人可以发表评论来帮助我理解这个问题吗?
没有问题。$(".test")
返回的对象类似于数组(行为类似于数组(,因此您可以像使用本机函数 document.querySelectorAll(".test")
一样访问它包含的元素。
它没有什么特别的。jQuery
所做的是使用本机函数来获取元素,然后将每个元素注入到其类似数组的对象中。查看下面的示例,了解如何制作简单的jQuery-like
函数。
例:
/* ----- JavaScript ----- */
function $ (selector) {
/* Check whether the context is a $ instance. */
if (this instanceof $) {
/* Get the elements matching the given selector. */
var elements = document.querySelectorAll(selector);
/* Set the length property of the object. */
this.length = 0;
/* Iterate over every element gotten. */
for (var i = 0, l = elements.length; i< l; i++) {
/* Inject each element in the object. */
this[i] = elements[i];
/* Increment the length. */
this.length++;
}
/* Cache the selector as a public property of the object. */
this.selector = selector;
}
else return new $(selector);
}
/* --- Use --- */
var elements = $(".test");
console.log(typeof elements);
console.log(elements[0]);
console.log(elements[1]);
console.log(elements[2]);
<!----- HTML ----->
<div id = "e1" class = "test"></div>
<div id = "e2" class = "test"></div>
<div id = "e3" class = "test"></div>
笔记:
- 试图通过阅读
jQuery
源代码来学习JavaScript
是一个坏主意。 - 为了使对象类似于数组,它必须具有:
- 数值属性(索引(,
- 数字
length
属性和 splice
方法(可选,在控制台中记录为数组(。