如果我在启动时有很多函数,它们都必须在一个单一的:
$(document).ready(function() {
或者我可以有多个这样的声明?
如果我在启动时有很多函数,它们都必须在一个单一的:
$(document).ready(function() {
或者我可以有多个这样的声明?
当前回答
是的,你可以很容易地拥有多个区块。只是要小心它们之间的依赖关系,因为求值顺序可能不是您所期望的。
其他回答
我认为更好的方法是把开关到命名函数(检查这个溢出关于这个主题的更多信息)。 这样您就可以从单个事件中调用它们。
像这样:
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();
});
检查这小提琴的工作版本
是的,你可以很容易地拥有多个区块。只是要小心它们之间的依赖关系,因为求值顺序可能不是您所期望的。
是的,你可以。
如果您有其他模块使用同一个页面,那么多个文档就绪部分将特别有用。用旧窗户。Onload =func声明,每次指定要调用的函数时,它都会替换旧的函数。
现在,所有指定的函数都被排队/堆叠(有人能确认吗?),而不管它们是在哪个文档准备部分中指定的。
您甚至可以在包含的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
你也可以这样做:
<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块中有多个未命名的函数时发现了这个问题-我无法得到正确的语法。我最终找到了答案,并希望通过发布我的测试代码来帮助其他人寻找我同样问题的答案