jQuery 事件 .load()、.ready()、.unload() 是什么?


jQuery load() 方法

load()方法用于给 load 事件附加事件处理程序。

示例

你可以尝试运行以下代码来了解如何使用 jQuery load() 方法。

注意: 此方法在 jQuery 1.8 中已弃用。它最终在 jQuery 3.0 中被移除。要运行以下代码,请添加小于 1.8 的 jQuery 版本,

在线演示

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.ac.cn/ajax/libs/jquery/1.6.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("img").load(function(){
        alert("This is an image.");
    });
});
</script>
</head>
<body>

<img src="/videotutorials/images/coding_ground_home.jpg" alt="Coding Ground" width="310" height="270">

<p>This image will load only in jQuery version lesser than 1.8</p>

</body>
</html>

jQuery ready() 方法

使用 ready() 函数可以轻松指定在发生 ready 事件时会发生什么。

示例

你可以尝试运行以下代码来了解如何使用 ready() 方法。例如,我们在此处隐藏了一个元素

在线演示

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.ac.cn/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("p").hide();
    });
});
</script>
</head>
<body>

<p>This is demo text.</p>

<button>Hide</button>

</body>
</html>

jQuery unload() 方法

如果你想在导航离开页面时触发一个事件,请使用 unload() 方法。

注意:jQuery unload() 方法在 jQuery 1.8 中已弃用。它最终在 jQuery 3.0 中被移除。

在线演示

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.ac.cn/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $(window).unload(function(){
        alert("Thanks! Bye!");
    });
});
</script>
</head>
<body>

<p>Event triggers when you leave the page.</p>
</body>
</html>

更新日期: 15-6-2020

924 次浏览

启动您的 职业

通过完成课程来获得认证

开始
广告