在 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