我应该等待文件准备好吗? [英] Should I wait for document ready?

查看:72
本文介绍了我应该等待文件准备好吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的代码中,我将事件处理程序绑定到文档

In my code I am binding event handlers to document:

$(document).bind("myEvent", function() { ... });

我是否必须等待就绪事件(即使用 $(文件) ).ready )一般情况下绑定事件处理程序,特别是当它绑定到文档时?

Do I have to wait for the ready event (i.e. use $(document).ready) to bind event handlers in general and when I bind them to document in particular?

推荐答案

$(document).ready 用于确保DOM在尝试与之交互之前就绪。如果您将脚本放在< head> 中,那么如果您与DOM交互,我建议您将代码放在此块中。如果你把你的脚本放在DOM元素之后的< body> 的底部,那么它不是必需的 - 但我仍然建议使用它。

$(document).ready is used to ensure the DOM is ready before trying to interact with it. If you put your script in the <head> then I suggest you put your code within this block if you interact with the DOM. If you put your script at the bottom of the <body> after the DOM elements then its not required - but I would still suggest its used.

更新

将事件处理程序附加到文档不要求代码在 ready 处理程序中,但它通常用于一致性,有些人(包括我)将所有脚本放在附加事件处理程序(无论是否目标)在 ready 处理程序中。

Attaching an event handler to the document doesn't require the code to be within the ready handler but its often used for consistency, some people (me included) place all script to attach event handers (regardless of the target) in a ready handler.

您会注意到的文档bind()在附加处理程序之前元素必须存在。

You will notice that on the documentation for bind() that elements must exist before the handler is attached.


处理程序附加到当前选定的元素在jQuery对象中,所以这些元素必须存在于调用.bind()的位置。

Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to .bind() occurs.

另请注意 .on()是从jQuery 1.7开始在 .bind()中使用的首选和建议方法

Also note that .on() is the preferred and suggested method to use inplace of .bind() as of jQuery 1.7

这篇关于我应该等待文件准备好吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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