你能有多个 $(document).ready(function(){ ... });部分? [英] Can you have multiple $(document).ready(function(){ ... }); sections?

查看:32
本文介绍了你能有多个 $(document).ready(function(){ ... });部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在启动时有很多功能,它们是否都必须在一个之下:

If I have a lot of functions on startup do they all have to be under one single:

$(document).ready(function() {

或者我可以有多个这样的语句吗?

or can I have multiple such statements?

推荐答案

您可以拥有多个方案,但这并不总是最好的做法.尽量不要过度使用它们,因为它会严重影响可读性.除此之外,这是完全合法的.请参阅以下内容:

You can have multiple ones, but it's not always the neatest thing to do. Try not to overuse them, as it will seriously affect readability. Other than that , it's perfectly legal. See the below:

http://www.learningjquery.com/2006/09/multiple-文档就绪

试试这个:

$(document).ready(function() {
    alert('Hello Tom!');
});

$(document).ready(function() {
    alert('Hello Jeff!');
});

$(document).ready(function() {
    alert('Hello Dexter!');
});

你会发现等价于这个,注意执行顺序:

You'll find that it's equivalent to this, note the order of execution:

$(document).ready(function() {
    alert('Hello Tom!');
    alert('Hello Jeff!');
    alert('Hello Dexter!');
});

还值得注意的是,在一个 $(document).ready 块中定义的函数不能从另一个 $(document).ready 块中调用,我刚刚运行本次测试:

It's also worth noting that a function defined within one $(document).ready block cannot be called from another $(document).ready block, I just ran this test:

$(document).ready(function() {
    alert('hello1');
    function saySomething() {
        alert('something');
    }
    saySomething();

});
$(document).ready(function() {
    alert('hello2');
    saySomething();
}); 

输出是:

hello1
something
hello2

这篇关于你能有多个 $(document).ready(function(){ ... });部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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