问题
I have a jQuery code as follows;
var favorites = $("#favorites");
var favoritesFooter = $("#favoritesFooter",favorites);
I am not sure what does the comma mean in the 2nd statement $("#favoritesFooter",favorites);
Also what would the following statement do or represent in the above case;
favoritesFooter.prev().after(newHTML);
回答1:
The second statement means "search for element with ID of favoritesFooter
inside the jQuery object favorites
".
As you're dealing with ID which should be unique, it's pointless - $("#favoritesFooter")
is the best practice.
Regarding favoritesFooter.prev()
it's also pointless, assuming the ID is unique so you have collection with only one element thus prev()
will return empty jQuery collection.
The .prev()
will take the previous DOM element - in your case, it will push newHTML
right before the favoritesFooter
element.
回答2:
It's the second parameter to $()
. As explained in the documentation:
Selector Context
By default, selectors perform their searches within the DOM starting at the document root. However, an alternate context can be given for the search by using the optional second parameter to the $() function. For example, to do a search within an event handler, the search can be restricted like so:
$('div.foo').click(function() {
$('span', this).addClass('bar');
});
When the search for the span selector is restricted to the context of this, only spans within the clicked element will get the additional class.
Internally, selector context is implemented with the .find() method, so $('span', this) is equivalent to $(this).find('span').
来源:https://stackoverflow.com/questions/6979097/what-does-the-second-argument-to-mean