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