$("#id")[0] 中的 [0] 有什么作用? [英] What does the [0] do in $("#id")[0]?
问题描述
我猜它是一个数组索引,但来自哪个数组?我见过它在这样的代码中使用:
I'm guessing that it's an array index, but from what array?I've seen it used in code like this:
HTML:
<canvas id = "id"> </canvas>
JavaScript/jQuery:
JavaScript/jQuery:
var canvas = $("#canvas")[0];
指定 [0]
部分的目的是什么,它与执行 var canvas = $("#canvas");
有何不同?
What is the purpose of specifying the [0]
part and how does it differ from doing var canvas = $("#canvas");
?
推荐答案
它是一种从 jQuery 集合中返回 DOM 节点的方法,也是一种更短的编写方式 document.getElementById('canvas')
(尽管使用了一个库),或者 $('#canvas').get(0);
.
It's a means of returning the DOM node from the jQuery collection, and a shorter way of writing document.getElementById('canvas')
(albeit using a library to do so), or $('#canvas').get(0);
.
实际上,它从 jQuery 选择器语法返回的对象集合中返回第一个(使用 JavaScript 的零索引编号)元素.
Effectively it returns the zeroeth-element, the first (using JavaScript's zero-indexed numbering) element, from the collection of objects returned by the jQuery selector syntax.
区别在于 $('#canvas')
返回一个包含元素集合的 jQuery 对象(使用 jQuery 方法包装在一个 jQuery 对象中),而 $('#canvas')[0]
返回 DOM 节点,该节点可以访问 DOM 方法,但不能访问 jQuery 方法.
The difference is that $('#canvas')
returns a jQuery object incorporating a collection of elements (wrapped in a jQuery object with jQuery methods), whereas $('#canvas')[0]
returns the DOM node, which has access to DOM methods, but not jQuery methods.
参考文献:
这篇关于$("#id")[0] 中的 [0] 有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!