为什么需要将$(document).ready添加到自执行函数中? [英] Why do I need to add $(document).ready to a self-executing function?

查看:202
本文介绍了为什么需要将$(document).ready添加到自执行函数中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是弄乱了一些JavaScript,发现了一些让我有些困惑的东西.

I'm just messing with some javascript and I came across something that puzzled me a little.

我已将指向脚本文件的链接添加到文档的标题中,紧接在指向jQuery的链接之后.

I've added a link to a script file into the header of a document, just after the link to jQuery.

如果我放置在测试文件中:

If I place in the test file:

(function($){


$("#thing").mouseover(function(){alert("woo");});


})(jQuery);

mouseover事件不会触发该功能.

The mouseover event does not trigger the function.

但是,如果我添加

(function($){

$(document).ready(function(){

$("#thing").mouseover(function(){alert("woo");});

});
})(jQuery);

该事件确实有效.

是否简单地没有$(document).ready,在我的自执行函数运行时DOM还没有完成加载,因此还没有#thing可以将函数附加到该函数,或者还有其他解释吗?

Is it simply that without $(document).ready the DOM hasn't finished loading at the point when my self-executing function runs, so there is no #thing yet to attach the function to or is there another explanation?

推荐答案

我已将指向脚本文件的链接添加到文档的标题

这就是重点.

通常,人们将脚本文件放在文档的页脚中以优化页面的加载过程,因此,无需等待文档准备好基于已加载的DOM执行某些操作(如果您位于页脚,您已经加载了其余的内容-除非您有一些内容需要异步加载.

Usually people put script files in the footer of document to optimize the process of loading the page, therefore it would not need to wait for the document to be ready to execute something based on the DOM already loaded (if you are in the footer, you have already loaded the rest - unless you have some content loading async).

尝试将脚本文件放在页脚中,这样就不需要$(document).ready.

Try putting your script file in the footer, and you will not need the $(document).ready.

摘要:在您的情况下,您需要它,因为当脚本开始执行时,您还没有开始寻找DOM,并且在那个时候找不到该元素.

Summary: In your case you need it, because when the script starts executing you have not started yet looking for the DOM, and the element cannot be found in that time.

这篇关于为什么需要将$(document).ready添加到自执行函数中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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