die() 是 live() 的伴生方法,用來移除以 live() 掛上的事件處理器。兩者一樣已在 jQuery 1.9 中一併移除。
$(selector).die(type, function)
參數:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>die 示例</title>
<style type="text/css">
div { border: 1px solid blue; }
li {
list-style-type: none;
width: 150px;
height: 150px;
border: 1px solid green;
}
</style>
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("div").live("click", function () {
$("li").slideToggle();
});
$("button").click(function () {
$("div").die();
});
});
</script>
</head>
<body>
<div>
<ul>
<li>博客園</li>
</ul>
</div>
<button>刪除添加</button>
</body>
</html>
按下按鈕後,稍後點擊 div 就不再觸發 slideToggle。
// 舊寫法
$("li").live("click", handler);
$("li").die("click", handler);
// 新寫法
$(document).on("click", "li", handler);
$(document).off("click", "li", handler);
移除時要注意:off() 的選擇器參數必須與 on() 時完全一致,否則找不到要移除的綁定。若當時有傳 handler,移除時也要傳同一個函式參考;否則可以用命名空間一次清掉:
$("#list").on("click.list", "li", handler);
$("#list").off(".list"); // 移除整個命名空間
維護舊專案時一定會遇到 live()/die()。若專案升上 jQuery 1.9+,這些呼叫會直接丟出「live is not a function」的錯誤。最省事的做法是引入 jquery-migrate 相容層過渡,但正解仍是把全部改寫成 on()/off()——毕竟它們的功能是 live()/die() 的完全超集。