I'm looking at an 开发者_如何学Cexample of how to use jqGrid, which is a jQuery plugin.
It's drawing a grid in a div with an id of 'list'.
It creates the grid with $('#list').jqGrid(...)
.
But it populates the grid with $('#list')[0].addJSONData(...)
.
I've been looking around the web for tutorials on jQuery, trying to understand the difference, and I've found nothing that addresses what is - to me - the most fundamental question in using it.
What does $()
return? Does it return a jquery object that contains a DOM element? Does it return a jquery object that contains an array of DOM elements? Does it return a DOM element to which additional jQuery functions have been added?
And what then, is $()[0]
? If $()
returned a jQuery object that contained an array of DOM elements, I'd expect it to be the div with the id 'list', but addJSONData
isn't a DOM method, it's a jqGrid method. Does jqGrid add that method to all of the DOM elements in the array?
===== ADDED ======
If $() returns a jquery object that contains an arrray of DOM objects, why does $()[0] refer to an object that contains an addJSONData method? addJSONData is not a DOM method, it's a jqGrid method.
$()
is a jquery selector, it takes css expression and turn it into jQuery object, $
is actually a shorthand of jQuery, i.e. jQuery()
and $()
are the same.
$()[0]
simply takes the non jQuery object, so if you do $('#someId')[0]
, it's the same as getElementById('someId');
$()
returns a collection of elements based on the selector. So $('.help')
would return all elements with a class of .help
. $('.help')[0]
would give you the first element.
$() is an alias for the jQuery() function. It returns a jQuery object and and elements that match the provided selector. If matched elements were found, $()[0] would give you the first DOM element.
See the jQuery documentation for a full explanation.
The jQuery object, when used with a selector, returns an array of DOM elements. In this case, $('#list')
represents an array (with one slot, since this is an ID) of items that match the ID '#list'
.
$() returns a jQuery object that contains a set of matched elements. Indexing into the jQuery object via $()[0] returns the first matched DOM object.
var docWrappedInJQuery = $('document');
var bareDoc = $('document')[0];
assert((document === docWrappedInJQuery) === false);
assert((document === bareDoc) === true);
$()
is the same as calling jQuery()
. Documentation is here: http://api.jquery.com/jQuery/
Keep in mind calling $(function() { })
is a shortcut to calling $(document).ready(function() { });
精彩评论