$(document)与$("document") [英] $(document) vs. $("document")

查看:157
本文介绍了$(document)与$("document")的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$(document)$("document")之间是否有区别?

也进入.ready()时,例如$("document").ready()

推荐答案

$(document)使用jQuery包装全局document对象.

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

$("document")尝试查找<document>元素,在HTML中显然没有意义,因为没有这样的元素,只有<html>元素表示的根document对象在标记中.之所以如此,是因为通过向jQuery函数传递字符串,实际上是为它提供了选择器.

$("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.

重新如 patrick dw 所说,在ready()的上下文中没什么区别,事实上,从jQuery 3.0开始,完全不使用$(document)或显式调用ready()是不推荐的.从文档:

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提供了几种附加功能的方法,这些功能将在DOM准备就绪时运行.以下所有语法均等效:

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 )
  • $( handler )
  • $( document ).ready( handler )
  • $( "document" ).ready( handler )
  • $( "img" ).ready( handler )
  • $().ready( handler )

从jQuery 3.0开始,仅建议使用第一种语法.其他语法仍然有效,但已弃用.这是因为选择与.ready()方法的行为无关,这是无效的,并且可能导致对该方法行为的错误假设.例如,第三种语法可与"document"一起使用,而不会选择任何内容.第四种语法等待文档准备就绪,但是(错误地)暗示它等待图像准备就绪.

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.

这篇关于$(document)与$("document")的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆