简体   繁体   English

$([])在jQuery中意味着什么?

[英]What does $([]) mean in jQuery?

var username = $("#username"),
                password = $("#password"),
                allFields = $([]).add(username).add(password);

What is allFields? 什么是全场? What is $([])? 什么是$([])?

Being a newbie to Javascript/jQuery, I've never seen this $([]) notation before and I'm interested in its associated methods. 作为Javascript / jQuery的新手,我以前从未见过这个$([])表示法,我对它的相关方法很感兴趣。

Given that its "$([])", it's tricky to search for. 鉴于它的“$([])”,搜索起来很棘手。 And a Google search of arrays in Javascript (guessing that thing is an array of some sort) yields the typical arrays I'm familiar seeing. 谷歌在Javascript中搜索数组(猜测那个东西是某种数组)产生了我熟悉的典型数组。

So what is $([])? 那么$([])是什么? Can anyone point me to some documentation? 谁能指点我一些文件? I'm interested in learning how to use this strange thing. 我有兴趣学习如何使用这个奇怪的东西。

The jQuery function accepts an array of DOM nodes. jQuery函数接受DOM节点数组。

$([document.body]) for example which will return a jQuery object by wrapping all the DOM elements passed in that array. $([document.body])例如,它将通过包装在该数组中传递的所有DOM元素来返回jQuery对象。 However, since in your example there is no DOM object to begin with and it's just an empty array, there is not need to even pass an empty array. 但是,因为在您的示例中没有开始的DOM对象,并且它只是一个空数组,所以甚至不需要传递空数组。

Calling the jQuery function without any arguments returns an empty set. 在没有任何参数的情况下调用jQuery函数会返回一个空集。 Taken from jQuery docs, 摘自jQuery文档,

Returning an Empty Set 返回空集

As of jQuery 1.4, calling the jQuery() method with no arguments returns an empty jQuery set. 从jQuery 1.4开始,调用不带参数的jQuery()方法会返回一个空的jQuery集。 In previous versions of jQuery, this would return a set containing the document node. 在以前版本的jQuery中,这将返回包含文档节点的集合。

So, your example would work the same if you had instead called 所以,如果您改为调用,那么您的示例将会起作用

$().add(username).add(password);

As other answers have mentioned and the docs say, passing an empty array was required before v 1.4. 正如其他答案所提到的那样,文档说,在v 1.4之前需要传递一个空数组。

[] it's an empty array. []这是一个空数组。 Wrapping it with $() overcharges it with jQuery's functions. 用$()包装它用jQuery的函数过度充电。

In javascript you can create an array this way: 在javascript中,您可以通过以下方式创建数组:

var foo = [];

It is an empty array being passed in the creation of a jQuery object. 它是一个在创建jQuery对象时传递的空数组。 Presumably to initialize something. 大概要初始化一些东西。

Shouldn't be necessary, at least not in the latest versions of jQuery. 不应该是必要的,至少不是最新版本的jQuery。

Here's an example without the Array: http://jsfiddle.net/MAzLN/ 这是没有数组的例子: http//jsfiddle.net/MAzLN/

Works fine, as the alert() shows one element in the object. 工作正常,因为alert()显示对象中的一个元素。

jQuery initializes the length property to 0 when the object is created, so I'm not sure what the purpose is, unless it was required in the past. 当创建对象时,jQuery将length属性初始化为0 ,所以我不确定目的是什么,除非过去需要它。

我相信它会创建一个空的jQuery集合对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM