这两种方法都在jQuery中使用。让我们看看他们实现什么目的。
$(窗口).load()
$(window).on(“ load”,function(){...})中包含的代码仅在整个页面准备就绪后运行(不仅是DOM)。
注意:该load()方法在jQuery 1.8版中已弃用。在3.0版中将其完全删除。要查看其工作原理,请在3.0之前添加CDN的jQuery版本。
$(document).ready()
该ready()方法用于在加载文档后使功能可用。一旦页面DOM准备执行JavaScript代码,您在$(document).ready()方法中编写的任何代码都将运行。
您可以尝试运行以下代码,以了解如何在jQuery中使用$(document).ready():
<html>
<head>
<title>jQuery Function</title>
<script src = "https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("div").click(function() {
alert("Hi!");
});
});
</script>
</head>
<body>
<div id = "mydiv">
Click on this to see a dialogue box.
</div>
</body>
</html>您可以尝试运行以下代码,以了解如何在jQuery中使用$(window).load():
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.staticfile.org/jquery/1.7.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("img").load(function(){
alert("图像成功加载。");
});
});
</script>
</head>
<body>
<img src="/videotutorials/images/tutor_connect_home.jpg" alt="Tutor Connect" width="310" height="220">
<p><strong>Note:</strong> The load() method deprecated in jQuery version 1.8. It was completely removed in version 3.0. To see its working, add jQuery version for CDN before 3.0.</p>
</body>
</html>