简体   繁体   中英

What does the jQuery selector $(“element”, $(document.body)) do?

I am trying to figure out what in the world this jquery selector is doing. When it runs, it is executing on a massive scale and removing it increases execution speed by roughly 95%. The optimized code works fine without it, but I am still trying to figure out what it was doing in the first place.

Here is the original code format:

$("[name='" + this.Name + "']", $(document.body))...

The item I'm trying to figure out is what is after the comma. It's not a normal part of the selector, as it is outside the main batch of quotes, and I have had no luck at all finding documentation on anything like this. When the code is reduced to

$("[name=\"" + this.Name + "\"]")

then it operates at a massively increased speed (95% faster). Does anyone know what that extra $(document.body) is doing?

The 2nd parameter to the $() function is the context . It's the same as doing:

$(document.body).find("[name='" + this.Name + "']")

(Which is completely useless as tags aren't normally outside the body of a document.)

PS You don't need to wrap the 2nd param in $() , it can be a DOM element (or even a selector).

$("[name='" + this.Name + "']", document.body) // this may be faster than
                                               // $(document.body)
$("[name='" + this.Name + "']", 'body')  // This is also valid

It's just defining the context that the selector should operate on. In your example it's explicitly setting the document body as the context but you could use any element in the DOM. Check out http://brandonaaron.net/blog/2009/06/24/understanding-the-context-in-jquery for a good discussion of the topic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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