$(document) vs. $(“document”)

2019-01-15 00:28发布

问题:

Is there any difference between: $(document) and $("document")?

EDIT: also when into the .ready() e.g. $("document").ready()

回答1:

$(document) uses jQuery to wrap the global document object.

$("document") attempts to look for a <document> element, which obviously makes no sense in HTML because there's no such element, only a root document object represented in the markup by the <html> element. It behaves that way because by passing the jQuery function a string, you're actually giving it a selector.

Re edit: as patrick dw says, in the context of ready() there's no difference, and in fact as of jQuery 3.0 using $(document) at all or explicitly calling ready() is deprecated. From the documentation:

jQuery offers several ways to attach a function that will run when the DOM is ready. All of the following syntaxes are equivalent:

  • $( handler )
  • $( document ).ready( handler )
  • $( "document" ).ready( handler )
  • $( "img" ).ready( handler )
  • $().ready( handler )

As of jQuery 3.0, only the first syntax is recommended; the other syntaxes still work but are deprecated. This is because the selection has no bearing on the behavior of the .ready() method, which is inefficient and can lead to incorrect assumptions about the method's behavior. For example, the third syntax works with "document" which selects nothing. The fourth syntax waits for the document to be ready but implies (incorrectly) that it waits for images to become ready.



回答2:

If you're talking about calling the .ready() function, it (currently) makes no difference.

In both cases the argument is ignored.

You could do this:

$( "cheese pizza" ).ready(function() {});

To be clear, it is best to use the officially supported calls to .ready(), which are:

$(document).ready(function(){/*...*/});

and:

$(function(){/*...*/});

When actually selecting the document, you should use $(document).



回答3:

Your first example wil search for an variable or object called document within your JS. (be carefull, it is a predefined variable)

The second will search the page for a tag with the name "document".

var document = 'div#logo';
$(document); //will search for div#logo
$('document'); //will search for document


回答4:

document is a pre-made global variable that is the representation of the current HTML document, short for window.document.

$("document"), as @BoltClock pointed out, would be using that string as a selector for a <document> element.