DIV CSS 佈局教程網

unbind() 移除事件綁定:全部移除、指定型別、指定函式
編輯:JQuery特效代碼     

unbind() 負責拆掉用 bind() 掛上的事件處理器,包含自訂事件。它的移除精度有三個層次,取決於你給它多少參數。

三種移除粒度

  • 不帶任何參數:刪除該元素上所有綁定的事件
  • 只給事件型別:只刪除該型別的綁定,例如 unbind('click')
  • 給事件型別加上函式參考:只刪除那一個特定的事件處理函式

語法

$(selector).unbind(type, function)

參數:

  • 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 移除,而且傳入的函式參考必須是同一個。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved