为什么$(document).ready()的位置很重要?

use*_*506 1 javascript jquery dom document-ready

我认为$(document).ready(...)中的脚本总是在加载DOM后执行.因此,如果一个$(document.ready(...)进入头部或正文中就没关系.但是,下面的代码不会像我想要的那样在屏幕上生成"苹果".如果我找到页面底部的giveApples()函数,它可以工作.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(giveApples());
function giveApples() {
    $("#appleTree").html("apples");
}
</script> 
</head>
<body>
<div id="appleTree"></div>
</body>
<script>
//$(document).ready(giveApples());
</script>
</html>
Run Code Online (Sandbox Code Playgroud)

任何人都可以请更正我对DOM,页面加载,脚本标记位置,(文档).ready()或其他任何导致此问题的误解吗?我还是网络编程的新手.

Mat*_*ens 13

那是因为你实际上没有将事件处理程序绑定到ready事件.你正在调用giveApples并将其返回值(undefined)作为事件处理程序传递给bind(它默默地失败).你需要传递函数.ready(),而不是调用它!

$(document).ready(giveApples);
Run Code Online (Sandbox Code Playgroud)

请注意缺少的括号.


Dan*_*nte 10

它没有.问题是你不是giveApples作为参数传递,而是传递它的返回值,因为你正在调用它(因为()).为了使它工作,不要把括号:

$(document).ready(giveApples);
Run Code Online (Sandbox Code Playgroud)

通过当前代码,传递给的值$(document).readyundefined,因为giveApples不返回任何值.

你也可以这样做:

$(document).ready(function(){
    giveApples();    //However, if you access the 'this' keyword inside the giveApples function, it will point to 'window', and not 'document'
});
Run Code Online (Sandbox Code Playgroud)

如果你有alert这两个值,你可以看到我上面解释的内容:

alert(giveApples);    //Shows the giveApples function body, properly
alert(giveApples());  //Shows undefined, since giveApples is being called and does not return any value
Run Code Online (Sandbox Code Playgroud)

它同样当您使用DOM事件(onload,onclick,等).你这样做:

window.onload = myFunction;
Run Code Online (Sandbox Code Playgroud)

并不是:

window.onload = myFunction();
Run Code Online (Sandbox Code Playgroud)