jQuery选择器后面的[]中的括号是什么意思? [英] What do [] brackets after a Jquery selector mean?

查看:478
本文介绍了jQuery选择器后面的[]中的括号是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此代码播放预加载的mp3文件.

I'm using this code to play a preloaded mp3 file.

var shuffle = $("#shuffle")[0]; 

shuffle.play();

随机播放是我的ID.我从网上获得了代码,但是我无法弄清楚jquery选择器后的[0]是什么.如果我将其删除,声音将无法播放.它能做什么?

Shuffle is my id. I got the code off the net but I CANNOT figure out what the [0] after the jquery selector does. The sound does not play if I remove it.What does it do?

谢谢

推荐答案

jQuery是一个类似于数组的对象,其中包含所有匹配的元素.通常,jQuery通常会默认将其更改应用于集合中的第一个元素:

jQuery is an array-like object that contains all of your matched elements. Often times, jQuery will by default apply its changes to the first element in the collection:

$("li").css("display"); // display val of first element, not all elements.

即使可以找到许多li元素,jQuery对象也会隐式地告诉我们第一个元素.我们可以使用$.get方法明确指示它这样做:

Even though many li elements could have been found, the jQuery object tells us about the first implicitly. We could explicitly instruct it to do so by using the $.get method:

$("li").get(0); // Returns first DOM element
$("li")[0]; // Also returns first DOM element

我们可以检查nodeName进行验证:

We could check the nodeName to verify this:

$("li").get(0).nodeName; // LI
$("li")[0].nodeName; // LI

如果我们仔细看一下,我们可以看到$.get()的实现方式:

If we look under the covers, we can see how $.get() is implemented:

get: function(num) {
  return num == null 
    ? this.toArray() 
    : ( num < 0 
          ? this[ this.length + num ] 
          : this[ num ] );
}

由此我们可以看到,当不提供任何参数时,整个元素集合将转换为数组,然后返回.当提供参数时,例如2,我们将元素返回为索引2.如果提供了-2,则将其添加到长度中(假设长度为5,5 +(-2)为3),并且所得的数字用作索引.

From this we can see that when no argument is provided, the entire collection of element is converted to an array, and then returned. When an argument is provided, for instance 2, we return the element as index 2. If -2 is provided, this is added to the length (suppose the length is 5, 5+(-2) is 3) and the resulting number is used as the index.

关于您的特定示例:

var shuffle = $("#shuffle")[0];
shuffle.play();

jQuery用于获取ID值为shuffle的任何元素.这将返回类似于jQuery数组的对象.但是您的play()方法不存在于jQuery对象上,它存在于#shuffle对象上.因此,您需要获取集合中的第一个元素.

jQuery is used to get any element that has the id value of shuffle. This returns the jQuery array-like object. But your play() method doesn't exist on the jQuery object, it exists on the #shuffle object. As such, you need to get the first element in the collection.

您可以使用$.get(0),但是正如我们刚刚看到的那样,这只会增加一个步骤.在内部,jQuery将执行与上面执行的相同的代码[0].

You could use $.get(0), however as we just saw, this would just be adding one more step. Internally, jQuery would perform the same code you're performing above, [0].

这篇关于jQuery选择器后面的[]中的括号是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆