Home > Article > Web Front-end > Detailed explanation of the correct way to cancel and bind jquery hover events
In web design, we often use jquery to respond to mouse hover events, which have the same effect as mouseover and mouseout events. But how to use on to bind the hover method? How to use off to cancel the bound event?
1. How to bind the hover event
First look at the following code. Suppose we bind a click and hover event to the a tag:
$(document).ready(function(){ $('a').on({ hover: function(e) { //Hover event handler alert("hover"); }, click: function(e) { // Click event handler alert("click"); } }); });
When the a tag is clicked, something strange happens. The bound hover event does not respond at all, but the bound click event responds normally.
But if you change the way of writing, for example:
$("a").hover(function(){ alert('mouseover'); }, function(){ alert('mouseout'); })
you should use mouseenter and mouseleave these two events instead, (this is also the event used in .hover() function)
So you can directly reference it like this:
$(document).ready(function(){ $('a').on({ mouseenter: function(e) { //Hover event handler alert("mouseover"); }, mouseleave: function(e) { //Hover event handler alert("mouseout"); }, click: function(e) { // Clickevent handler alert("click"); } }); });
Because .hover() is an event defined by jQuery itself, it is just for the convenience of users to bind and call mouseenter and mouseleave events. It is not a real event, so of course it cannot be regarded as .on( ) to call the event parameters in. 2. How to cancel the hover event
As we all know, you can use the off function to cancel the bound event, but you can only cancel the event bound through bind. The hover event in jquery is quite special. If you pass Events bound in this way cannot be canceled.
$("a").hover(function(){ alert('mouseover'); }, function(){ alert('mouseout'); })
The correct way to cancel a bound hover event:
$('a').off('mouseenter').unbind('mouseleave');
The above is the detailed content of Detailed explanation of the correct way to cancel and bind jquery hover events. For more information, please follow other related articles on the PHP Chinese website!