jquery对象如何使用索引来访问像数组一样的DOM



我知道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>


笔记:

  1. 试图通过阅读jQuery源代码来学习JavaScript是一个坏主意。
  2. 为了使对象类似于数组,它必须具有:
    • 数值属性(索引(
    • 数字length属性和
    • splice方法(可选,在控制台中记录为数组(。

相关内容

最新更新