gpt4 book ai didi

javascript - 为什么使用 jQuery 加载文档时不能直接调用函数?

转载 作者:行者123 更新时间:2023-11-28 16:17:01 25 4
gpt4 key购买 nike

我使用 jQuery 中的 $(document).ready 函数。看来我不能直接用它调用函数。我不明白为什么。当我尝试使用 getElementById 查找 Canvas 时出现错误。

这有效:

<!DOCTYPE html>
<html>
<head>
<script language="javascript" src="http://code.jquery.com/jquery-1.4.2.js" ></script>
<script type="text/javascript">
var test="this is a test";
var canvas;
var ctx;

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

function init() {
console.log (test);
canvas=document.getElementById('canvas');
ctx = canvas.getContext('2d');
}

</script>

</head>

<body>
<div>
<canvas id="canvas" width="300" height="300">
No HTML5 support.
</canvas>
</div>
</body>

</html>

这也有效:

<!DOCTYPE html>
<html>
<head>
<script language="javascript" src="http://code.jquery.com/jquery-1.4.2.js" ></script>
<script type="text/javascript">
var test="this is a test";
var canvas;
var ctx;

$(document).ready(function(){
console.log (test);
canvas=document.getElementById('canvas');
ctx = canvas.getContext('2d');
});


</script>

</head>

<body>
<div>
<canvas id="canvas" width="300" height="300">
No HTML5 support.
</canvas>
</div>
</body>

</html>

但这会产生错误...

<!DOCTYPE html>
<html>
<head>
<script language="javascript" src="http://code.jquery.com/jquery-1.4.2.js" ></script>
<script type="text/javascript">
var test="this is a test";
var canvas;
var ctx;

$(document).ready(init());

function init() {
console.log (test);
canvas=document.getElementById('canvas'); // <= Error here!
ctx = canvas.getContext('2d');
}


</script>

</head>

<body>
<div>
<canvas id="canvas" width="300" height="300">
No HTML5 support.
</canvas>
</div>
</body>

</html>

亲切的问候!

最佳答案

在这一行:

$(document).ready(init()); 

您实际上是立即调用 init 函数并将其结果作为参数传递给ready 函数。由于此行在 DOM 准备好之前执行,因此 init 函数失败。

您想更改为:

$(document).ready(init); 

也就是说,将实际的 init 函数而不是它的结果传递给ready 函数。

关于javascript - 为什么使用 jQuery 加载文档时不能直接调用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11201525/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com