如何使用 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>
廣告