jQuery的ready()方法的快捷方式
我已经看到了ready()方法的一些快捷方式,并且想知道哪个实际上首先发生,因为我的测试结果让我感到困惑。
$(document).ready(function(){
alert("document ready");
});
$(window).load(function(){
alert("window ready");
});
(function($){
alert("self invoke");
})(jQuery);
这里首先发生自调用,然后是文档,然后是窗口。 自调用技术是否被视为ready()方法?
I have seen some shortcuts for the ready() method and would like to know which actually happens first, because my test results confuse me..
$(document).ready(function(){
alert("document ready");
});
$(window).load(function(){
alert("window ready");
});
(function($){
alert("self invoke");
})(jQuery);
Here self invoke happens first, then document, then window. Is the self invoke technique considered a ready() method?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
第三个选项不是
.ready()
(或实际上与 jQuery 相关)的快捷方式,自调用立即运行(一旦出现在代码中),< em>这可能是您正在考虑的快捷方式:将函数传递到
$(func)
是$(document).ready(func);
的快捷方式。 无冲突 版本如下所示:The third option is not a shortcut for
.ready()
(or jQuery related really), the self invoke runs immediately (as soon as it appears in the code), this is probably the shortcut you're thinking of though:Passing a function into
$(func)
is a shortcut for$(document).ready(func);
. The no-conflict version would look like this:Nick Craver 的说法是正确的,但我认为值得注意的是,在最后一个示例中,它实际上根本没有对 jquery 执行任何操作。 jQuery 作为参数传递给匿名函数,但该函数没有对其执行任何操作。
最后一个示例相当于立即调用函数表达式 (IIFE):
显然,这只是在该行代码被命中后立即调用匿名函数,从而发出警报。它根本没有调用 jQuery,这就是为什么 Nick 说它绝对不是一个 read() 方法是正确的。
Nick Craver is right in what he says but I think it is worth noting that in that last example that it isn't actually doing anything with jquery at all. jQuery is being passed as a parameter to the anonymous function but the function isn't doing anything with it.
The last example is equivalent to an Immediately-Invoked Function Expression (IIFE):
And clearly this is just immediately calling the anonymous function as soon as that line of code is being hit and thus doing the alert. It isn't invoking jQuery at all which is why Nick is right when he says it is defintiely not a ready() method.
这篇文章很好地解释了前两者如何是不同的:
This article has a good explanation on how the first two are different: