jQuery 中 $(window).load() 和 $(document).ready() 函式有何不同?
這兩種方法均用於 jQuery。來看看它們分別有何用。
$(window).load()
包含在 $( window ).on( "load", function() { ... }) 中的程式碼僅在整個頁面準備就緒(而不僅僅是 DOM)後執行一次。
注意:自 jQuery 1.8 版本起,load() 方法已被棄用。它在 3.0 版中被徹底刪除。要檢視其執行情況,請在 3.0 版之前新增用於 CDN 的 jQuery 版本。
$(document).ready()
ready() 方法用於在文件載入後使函式可用。無論在 $( document ).ready() 方法中編寫什麼程式碼,都將在頁面 DOM 準備好執行 JavaScript 程式碼後執行一次。
你可以嘗試執行以下程式碼來學習如何在 jQuery 中使用 $(document).ready()
<html>
<head>
<title>jQuery Function</title>
<script src = "https://ajax.googleapis.com/ajax/libs/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://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("img").load(function(){
alert("Image successfully loaded.");
});
});
</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>
廣告
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP