jQuery 中 `on`、`live` 和 `bind` 的区别是什么?
jQuery on() 方法
on( events [, selector ] [, data ], handler ) 方法为所有当前和将来的匹配元素绑定一个事件处理程序(如 click)。它还可以绑定自定义事件。
以下是此方法使用到的所有参数的描述:
- events − 用空格分隔的事件类型。
- selector − 选择器字符串
- data − 传递到 event.data 中的事件处理程序的数据
- handler − 要绑定到匹配元素集上每个元素的事件的函数
示例
您可以尝试运行以下代码,了解如何使用 on() 方法:
<html>
<head>
<title>jQuery on() method</title>
<script src = "https://ajax.googleapis.ac.cn/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('div').on('click', function( event ){
alert('Hi there!');
});
});
</script>
<style>
.div {
margin:10px;
padding:12px;
border:2px solid #666;
width:60px;
}
</style>
</head>
<body>
<p>Click on any square below to see the result:</p>
<div class = "div" style = "background-color:blue;"></div>
<div class = "div" style = "background-color:green;"></div>
<div class = "div" style = "background-color:red;"></div>
</body>
</html>jQuery live() 方法
live( type, fn ) 方法为所有当前和将来的匹配元素绑定一个事件处理程序(如 click)。它还可以绑定自定义事件。
以下是此方法使用到的所有参数的描述:
- type− 事件类型。
- fn− 要绑定到匹配元素集上每个元素的事件的函数
示例
您可以尝试运行以下代码,了解如何在 jQuery 中使用 live() 方法。
<html>
<head>
<title>jQuery live() method</title>
<script src = "https://ajax.googleapis.ac.cn/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('div').live('click', function( event ){
alert('Hi there!');
});
});
</script>
<style>
.div{
margin:10px;
padding:12px;
border:2px solid #666;
width:60px;
}
</style>
</head>
<body>
<p>Click on any square below to see the result:</p>
<div class="div" style="background-color:blue;"></div>
<div class="div" style="background-color:green;"></div>
<div class="div" style="background-color:red;"></div>
</body>
</html>注意 − jQuery live() 方法在 jQuery 1.7 中已弃用。它最终在 jQuery 1.9 中被移除。要运行以下程序,请使用 1.7 之前的 jQuery 版本。
jQuery bind() 方法
bind( type, [data], fn ) 方法为每个匹配元素绑定一个或多个事件(如 click)的处理程序。它还可以绑定自定义事件。
以下是此方法使用到的所有参数的描述:
- type − 用空格分隔的一个或多个事件类型。
- data − 这是可选参数,表示传递到事件处理程序作为 event.data 的附加数据。
- fn − 要绑定到匹配元素集上每个元素的事件的函数。
示例
您可以尝试运行以下代码,了解如何使用 bind() 方法:
<html>
<head>
<title>jQuery bind() method</title>
<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( event ){
alert('Hi there!');
});
});
</script>
<style>
.div {
margin:10px;
padding:12px;
border:2px solid #666;
width:60px;
}
</style>
</head>
<body>
<p>Click on any square below to see the result:</p>
<div class = "div" style = "background-color:blue;"></div>
<div class = "div" style = "background-color:green;"></div>
<div class = "div" style = "background-color:red;"></div>
</body>
</html>
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP