如果我在启动时有很多函数,它们都必须在一个单一的:

$(document).ready(function() {

或者我可以有多个这样的声明?


当前回答

这是合法的,但有时会导致不良行为。作为一个例子,我使用MagicSuggest库,并在我的项目的一个页面中添加了两个MagicSuggest输入,并为每个输入的初始化使用了单独的文档就绪函数。第一个输入初始化成功了,但第二个没有,也没有给出任何错误,第二个输入没有显示。所以,我总是建议使用一个文档准备函数。

其他回答

我认为更好的方法是把开关到命名函数(检查这个溢出关于这个主题的更多信息)。 这样您就可以从单个事件中调用它们。

像这样:

function firstFunction() {
    console.log("first");
}

function secondFunction() {
    console.log("second");
}


function thirdFunction() {
    console.log("third");
}

这样就可以在一个就绪函数中加载它们。

jQuery(document).on('ready', function(){
   firstFunction();
   secondFunction();
   thirdFunction();

});

这将输出以下到您的console.log:

first
second
third

这样就可以为其他事件重用这些函数。

jQuery(window).on('resize',function(){
    secondFunction();
});

检查这小提琴的工作版本

是的,这是可能的,但你可以更好地使用一个div #mydiv和使用两者

$(document).ready(function(){});

//and

$("#mydiv").ready(function(){});

您甚至可以在包含的html文件中嵌套文档就绪函数。下面是一个使用jquery的例子:

文件:test_main.html

<!DOCTYPE html>
<html lang="en">
<head>
    <script src="jquery-1.10.2.min.js"></script>
</head>

<body>
    <div id="main-container">
        <h1>test_main.html</h1>
    </div>

<script>
    $(document).ready( function()
    {
        console.log( 'test_main.html READY' );
        $("#main-container").load("test_embed.html");
    } );
</script>

</body>
</html>

文件:test_embed.html

<h1>test_embed.html</h1>
<script>
    $(document).ready( function()
    {
        console.log( 'test_embed.html READY' );
    } );
</script>

控制台输出:

test_main.html READY                       test_main.html:15
test_embed.html READY                      (program):4

浏览器显示:

test_embed.html

你可以有多个,但这并不总是最明智的做法。尽量不要过度使用,因为这会严重影响可读性。除此之外,这完全合法。请看以下内容:

http://www.learningjquery.com/2006/09/multiple-document-ready

试试这个吧:

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

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

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

你会发现它和这个是等价的,注意执行顺序:

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

还有一点值得注意的是,在$(文档)中定义的函数。Ready块不能从另一个$(document)调用。ready block,我刚刚运行了这个测试:

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

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

输出是:

hello1
something
hello2

你可以使用multiple。但是您也可以在一个文档中使用多个函数。准备好了:

$(document).ready(function() {
    // Jquery
    $('.hide').hide();
    $('.test').each(function() {
       $(this).fadeIn();
    });

    // Reqular JS
    function test(word) {
       alert(word);
    }
    test('hello!');
});