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.com/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.com/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.com/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