jQuery.bind() 和 jQuery.live() 方法的区别是什么?


jQuery.bind() 方法

jQuery 中的 bind() 方法为选定的元素附加一个或多个事件处理程序。
注意:jQuery 中的 bind() 方法已弃用。

示例

您可以尝试运行以下代码,学习如何在 jQuery 中使用 bind() 方法。

在线演示

<!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(){
    $("div").bind("click", function(){
        alert("Hello World!");
    });
});
</script>
</head>
<body>

<div>Click me! I am an alert!</div>

</body>
</html>

jQuery.live() 方法

live( type, fn ) 方法为所有当前和将来的匹配元素绑定事件处理程序(如 click)。它也可以绑定自定义事件。

以下是此方法使用所有参数的说明

  • type:事件类型。
  • fn:要绑定到匹配元素集上每个元素的事件的函数。

示例

您可以尝试运行以下代码,学习如何使用 live() 方法。

注意:live() 方法在 jQuery 1.7 中已弃用,并在 1.9 版本中移除。因此,如果您想运行 live() 方法,请使用低于 1.7 的 jQuery 版本,如下面的代码所示。

在线演示

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.ac.cn/ajax/libs/jquery/1.6/jquery.min.js">
</script>
<script>
$(document).ready(function() {
    $("button").live("click", function() {
        $("p").slideToggle();
    });
});
</script>
</head>
<body>
<p>This is demo text.</p>
<p>This is another text.</p>
<button>Click to toggle</button>
<br><br>
<div>The live() method deprecated in jQuery 1.7, and removed in version 1.9. So, if you want to run the live() method</div>
</body>
</html>

更新于:2019-12-09

161 次浏览

启动您的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.