如何使用jQuery删除事件处理程序?
一旦建立了事件处理程序,该事件处理程序将在页面的剩余生命周期内保持有效。当您想删除事件处理程序时,可能会需要。
jQuery提供了unbind()
删除现有事件处理程序的命令。的语法unbind()
如下。
以下是参数的说明-
eventType- 包含JavaScript事件类型的字符串,例如click或Submit。有关事件类型的完整列表,请参见下一部分。
handler- 如果提供,则标识要删除的特定侦听器。
示例
您可以尝试运行以下代码,以了解如何使用jQuery删除事件处理程序-
<html> <head> <title>jQuery Unbind</title> <script src = "https://cdn.staticfile.org/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("可以点击!"); }); $("#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>