我知道 jQuery
函数 $("selector")
返回一个对象。
var divTest = $(".test"); // returns object
Array.isArray(divTest); // false
typeof divTest; // "object"
使用这个由jQuery
函数包装的对象,我们可以使用jQuery
的API。
我无法理解的一点是我们如何使用 jQuery
对象中的索引访问 native 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")
返回的对象是类似数组的(行为类似于数组),因此您可以按照与以下相同的方式访问它包含的元素:您使用的是 native 函数 document.querySelectorAll(".test")
。
没有什么特别的。 jQuery 的作用是使用 native 函数获取元素,然后将每个元素注入(inject)到其类似数组的对象中。查看下面的示例,了解如何制作一个简单的类 jQuery
函数。
示例:
/* ----- 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
方法(可选,在控制台中以数组形式记录)。
关于javascript - jquery对象如何像数组一样使用索引访问DOM?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48146179/