What does $([]) mean in jQuery
I have come across the following jQuery code but could not understand it. What does the following code, specially the "$([])" part in the last line mean ?
var instrument = $("#instrument"),
quantity = $("#quantity"),
orderType = $("#orderType"),
price = $("#price"),
validityDate = 开发者_如何学Go$("#validityDate"),
allFields = $([]).add(instrument).add(quantity).add(orderType).add(price).add(validityDate)
Looks like it's defining an array, then add()ing the DOM elements to it. From the manual:
Given a jQuery object that represents a set of DOM elements, the .add() method constructs a new jQuery object from the union of those elements and the ones passed into the method. The argument to .add() can be pretty much anything that $() accepts, including a jQuery selector expression, references to DOM elements, or an HTML snippet.
[]
is an empty javascript array. As frunsi notes, this is not correct usage, and the []
definition is not required to create an empty set of elements, in 1.4 $()
will do ths for you.
It creates an empty jQuery set. This kind of usage is wrong, though it may work. The []
is superfluous.
Correct would be just $()
.
Returning an Empty Set
As of jQuery 1.4, calling the jQuery() method with no arguments returns an empty jQuery set. In previous versions of jQuery, this would return a set containing the document node.
http://api.jquery.com/jQuery/
That would create an empty jQuery object - i.e. with a collection of 0 referenced DOM nodes.
Most often, you would find the jQuery function $
applied to either a CSS selector, a single or several nodes from the DOM. In this particular case, the last of these three "overloads" is used, to construct an empty jQuery object from an empty array, to which new DOM nodes are then added using add()
.
Your particular code sample is a bit verbose, though, as the same could have been achieved like this:
var allFields = $("#instrument, #quantity, #orderType, #price, #validityDate");
精彩评论