Method: 1. Use the "click element object.unbind("click");" method, which can remove the event handler of the selected element; 2. Use "click element object.off(" click");" method, which can remove the event handler added through the on() method.
The operating environment of this tutorial: Windows 10 system, JavaScript version 1.8.5, Dell G3 computer.
Method 1. Use the unbind() method
unbind() method to remove the event of the selected element handler.
This method can remove all or selected event handlers, or terminate the execution of the specified function when an event occurs.
This method can also unbind the event handler through the event object. This method is also used to unbind events within itself (such as deleting the event handler after the event has been triggered a certain number of times).
Note: If no parameters are specified, the unbind() method will remove all event handlers for the specified element.
Note: The unbind() method applies to any event handler added by jQuery.
The example is as follows:
<html> <head> <script type="text/javascript" src="/jquery/jquery.js"></script> <script type="text/javascript"> $(document).ready(function(){ $(".dianji").click(function(){ $("p").slideToggle(); }); $(".yichu").click(function(){ $(".dianji").unbind("click"); }); }); </script> </head> <body> <p>这是一个段落。</p> <button class="dianji">点击事件</button> <button class="yichu">移除点击事件</button> </body> </html>
Output result:
##Method 2, use off() method
The off() method is usually used to remove event handlers added through the on() method. As of jQuery version 1.7, the off() method is the new replacement for the unbind(), die(), and undelegate() methods. This method brings a lot of convenience to the API and is recommended because it simplifies the jQuery code base. Note: To remove a specified event handler, the selector string must match the parameter passed in the on() method when the event handler is added. The example is as follows:<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>123</title> <script src="js/jquery.min.js"> </script> <script> $(document).ready(function(){ $("p").on("click",function(){ $(this).css("background-color","pink"); }); $("button").click(function(){ $("p").off("click"); }); }); </script> </head> <body> <p>点击这个段落修改它的背景颜色。</p> <p>点击一下按钮再点击这个段落( click 事件被移除 )。</p> <button>移除 click 事件句柄</button> </body> </html>
##[Related recommendations:
javascript video tutorialThe above is the detailed content of How to remove element click event in javascript. For more information, please follow other related articles on the PHP Chinese website!