jQuery document.ready [英] jQuery document.ready

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

问题描述

我对jQuery中的document.ready感到有点困惑。

I am a little confused with document.ready in jQuery.

你什么时候在
$(document).ready()中定义javascript函数什么时候不用?

When do you define javascript functions inside of $(document).ready() and when do you not?

将所有javascript代码放在$(document).ready()中是否足够安全?

Is it safe enough just to put all javascript code inside of $(document).ready()?

当你不这样做时会发生什么?

What happens when you don't do this?

例如,我使用通常的jQuery选择器,当你点击东西时它会做一些事情。如果你没有用document.ready包装它们有什么危害呢?

For example, I use the usual jQuery selectors which do something when you click on stuff. If you don't wrap these with document.ready what is the harm?

如果有人在分裂之前点击了分裂的元素,它是否只会导致问题页面已加载?或者它会导致其他问题吗?

Is it only going to cause problems if someone clicks on the element in the split second before the page has loaded? Or can it cause other problems?

推荐答案

document.ready 处理程序当浏览器加载DOM并准备进行操作时触发。

The document.ready handler is triggered when the DOM has been loaded by the browser and ready to be manipulated.

您是否应该使用它取决于您放置自定义脚本的位置。如果您将它们放在文档的末尾,就在结束< / body> 标记之前,您不需要使用 document.ready 因为当你的脚本执行时,DOM已经被加载,你将能够操作它。

Whether you should use it or not will depend on where you are putting your custom scripts. If you put them at the end of the document, just before the closing </body> tag you don't need to use document.ready because by the time your script executes the DOM will already be loaded and you will be able to manipulate it.

另一方面,如果您将脚本放在文档的< head> 部分,您应该使用 document.ready 确保在尝试修改DOM或将事件处理程序附加到各种元素之前完全加载DOM。如果您不这样做并且尝试将 .click 事件处理程序附加到按钮,则永远不会触发此事件,因为在脚本运行时,您用于查找按钮的jQuery选择器未返回任何元素,并且您未成功附加处理程序。

If on the other hand you put your script in the <head> section of the document you should use document.ready to ensure that the DOM is fully loaded before attempting to modify it or attach event handlers to various elements. If you don't do this and you attempt to attach for example a .click event handler to a button, this event will never be triggered because at the moment your script ran, the jQuery selector that you used to find the button didn't return any elements and you didn't successfully attach the handler.

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

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