如何使用 jQuery 移除事件處理器?
一旦建立了事件處理器,它在頁面生命週期中就會一直有效。有時你可能需要移除事件處理器。
jQuery 提供 unbind() 命令來移除現有的事件處理器。unbind() 的語法如下。
以下是對引數的描述 −
- eventType − 一個包含 JavaScript 事件型別(如 click 或 submit)的字串。有關事件型別的完整列表,請參閱下一部分。
- handler − 如果提供了,則標識要移除的特定偵聽器。
示例
你可以嘗試執行以下程式碼,瞭解如何使用 jQuery 移除事件處理器 −
<html>
<head>
<title>jQuery Unbind</title>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
function aClick() {
$("div").show().fadeOut("slow");
}
$("#bind").click(function () {
$("#theone").click(aClick).text("Can Click!");
});
$("#unbind").click(function () {
$("#theone").unbind('click', aClick).text("Does nothing...");
});
});
</script>
<style>
button {
margin:5px;
}
button#theone {
color:red;
background:yellow;
}
</style>
</head>
<body>
<button id = "theone">Does nothing...</button>
<button id = "bind">Bind Click</button>
<button id = "unbind">Unbind Click</button>
<div style = "display:none;">Click!</div>
</body>
</html>
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP