在 jQuery 中建立頁面載入事件

Sheeraz Gul 2024年2月15日
在 jQuery 中建立頁面載入事件

帶有 load 事件的 on() 方法用於在 jQuery 中建立頁面載入事件。本教程演示如何在 jQuery 中建立頁面載入事件。

在 jQuery 中建立頁面載入事件

以前,jQuery 有函式 load(),它用作頁面載入或 document.ready 事件,但此方法在 jQuery 版本 1.8 中已棄用並在版本 3.0 中刪除。現在,on() 方法可以與 load 事件一起使用,以便在頁面完全載入後執行操作。

帶有 load 事件的 on() 方法在頁面上載入所有內容時起作用,包括樣式表、影象、視訊等。

on() 方法的語法是:

$(window).on('load', functionforOnPageLoad() )

頁面完全載入時將呼叫該函式的位置。讓我們嘗試一個例子:

<!DOCTYPE html>
<html>

<head>
    <title> jQuery On Page Load </title>

    <script src="https://code.jquery.com/jquery-3.3.1.min.js"> </script>
</head>

<body>

    <script type="text/javascript">
        $(window).on('load', AlertMessage());

        function AlertMessage() {
            alert("Hello This is Page is fully loaded");
        }
    </script>
</body>

</html>

上面的程式碼將在頁面完全載入時提醒訊息。見輸出:

jQuery 頁面載入警報

讓我們嘗試另一個示例來顯示頁面完全載入後的當前時間。參見示例:

<!DOCTYPE html>
<html>

<head>
    <title> jQuery On Page Load </title>

    <script src="https://code.jquery.com/jquery-3.3.1.min.js"> </script>
</head>
<body>

    <p> The current Time is: </p>
    <span class="date"></span>

    <script type="text/javascript">
        $(window).on('load', ShowCurrentTime());

        function ShowCurrentTime() {
            document.querySelector("span").textContent = new Date();
        }
    </script>
</body>
</html>

頁面完全載入後,上面的程式碼將顯示當前時間。見輸出:

頁面載入時的 jQuery

作者: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook

相關文章 - jQuery Event