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

$(document).ready(function() {

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


当前回答

你也可以这样做:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
 $(document).ready(function(){
     $("#hide").click(function(){
     $("#test").hide();
     });
     $("#show").click(function(){
     $("#test").show();
     });
 });
</script>
</head>

<body>
<h2>This is a test of jQuery!</h2>
<p id="test">This is a hidden paragraph.</p>
<button id="hide">Click me to hide</button>
<button id="show">Click me to show</button>
</body>

前面的答案显示了在单个.ready块中使用多个命名函数,或者在.ready块中使用单个未命名函数,在.ready块外使用另一个已命名函数。我在研究是否有一种方法可以在.ready块中有多个未命名的函数时发现了这个问题-我无法得到正确的语法。我最终找到了答案,并希望通过发布我的测试代码来帮助其他人寻找我同样问题的答案

其他回答

你也可以这样做:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
 $(document).ready(function(){
     $("#hide").click(function(){
     $("#test").hide();
     });
     $("#show").click(function(){
     $("#test").show();
     });
 });
</script>
</head>

<body>
<h2>This is a test of jQuery!</h2>
<p id="test">This is a hidden paragraph.</p>
<button id="hide">Click me to hide</button>
<button id="show">Click me to show</button>
</body>

前面的答案显示了在单个.ready块中使用多个命名函数,或者在.ready块中使用单个未命名函数,在.ready块外使用另一个已命名函数。我在研究是否有一种方法可以在.ready块中有多个未命名的函数时发现了这个问题-我无法得到正确的语法。我最终找到了答案,并希望通过发布我的测试代码来帮助其他人寻找我同样问题的答案

是的,可以有多个$(document).ready()调用。然而,我不认为你能知道他们将以何种方式执行。(源)

是的,完全没问题。但是要避免没有理由就这么做。例如,当我的javascript文件动态生成时,我使用它来声明全局站点规则,而不是单独的页面,但如果你只是不断地这样做,它会使它难以阅读。

另外,您不能从另一个方法访问某些方法 jQuery(函数(){});调用 这是你不想这么做的另一个原因。

用旧窗户。Onload,但你将替换旧的每次你指定一个函数。

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

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

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

像这样:

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();
});

检查这小提琴的工作版本