unbind() 負責拆掉用 bind() 掛上的事件處理器,包含自訂事件。它的移除精度有三個層次,取決於你給它多少參數。
unbind('click')$(selector).unbind(type, function)
參數:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>unbind 示例</title>
<style type="text/css">
div {
width: 200px;
height: 200px;
background-color: blue;
text-align: center;
line-height: 200px;
}
</style>
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("div").click(function () {
$("div").append("添加的內容");
});
$("button").click(function () {
$("div").unbind();
});
});
</script>
</head>
<body>
<div></div>
<button>刪除事件</button>
</body>
</html>
按下按鈕後,div 上註冊的 click 處理函式被移除,之後點擊 div 不再有任何反應。
如果你想精準移除某一個 handler,就不能用匿名函式綁定它——因為你手上沒有函式參考可以傳給 unbind():
// 綁定時沒有保留參考,之後無法單獨移除
$("button").click(function () { doSomething(); });
// 正確做法:先命名,再移除
function handler() { doSomething(); }
$("button").on("click", handler);
$("button").off("click", handler);
另一個技巧是使用命名空間,可以一次移除某一批事件而不影響其他:
$("button").on("click.myPlugin", handler);
$("button").off(".myPlugin"); // 只移除 myPlugin 命名空間下的所有事件
unbind() 在 jQuery 1.7 之後已被 off() 取代(bind() 對應 on())。兩者移除規則完全相同,但 off() 多支援事件委派形式的移除:
$(document).on("click", ".dynamic-btn", handler);
$(document).off("click", ".dynamic-btn", handler);
另外提醒:unbind() 只移除透過 jQuery 綁定的處理器。用原生 addEventListener 掛上的函式,必須用 removeEventListener 移除,而且傳入的函式參考必須是同一個。