Home > Article > Web Front-end > How to delete hover event in jquery
In jquery, you can use the unbind() method to delete the hover event; but you cannot directly use the "unbind("hover")" statement, because hover is composed of mouseenter and mouseleave, so you need to delete the hover effect. , just need to remove these two events, the syntax is "element object.unbind("mouseenter").unbind("mouseleave")".
The operating environment of this tutorial: windows7 system, jquery3.6.1 version, Dell G3 computer.
Today I encountered the problem of jquery needing to remove hover. I thought it could be solved by just unbind("hover")
, but it took a long time to solve it but it didn't work.
$("button").click(function() { $("p").unbind("hover"); });
The reason is actually very simple, hover is not an event. Open the reference manual, hover is actually composed of mouseenter and mouseleave. This makes the problem very clear!
/* 这种方法是错误的 */ $(#hover_div).unbind("hover"); /* 这种方法也是错误的 */ $(#hover_div).unbind("mouseover").unbind("mouseout"); /* 这种方法是新增的,在老的版本里是无法使用的 */ $(#hover_div).unbind("mouseenter mouseleave"); /* 这种方法正确的,新老版本皆可用 */ $(#hover_div).unbind("mouseenter").unbind("mouseleave");
The above code recommends using the fourth method, which is relatively safer.
Usage example:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="js/jquery-3.6.1.min.js"></script> <script> $(document).ready(function() { $("p").hover(function() { $("p").css("background-color", "yellow"); }, function() { $("p").css("background-color", "pink"); }); $("button").click(function() { $("p").unbind("mouseenter").unbind("mouseleave"); }); }); </script> </head> <body> <p>鼠标移动到该段落。</p> <button>删除hover</button> </body> </html>
Description: unbind() method
unbind The () method can remove all or selected event handlers, or terminate the execution of the specified function when the 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).
[Recommended learning: jQuery video tutorial, web front-end video]
The above is the detailed content of How to delete hover event in jquery. For more information, please follow other related articles on the PHP Chinese website!