Home > Web Front-end > JS Tutorial > Detailed explanation of the correct way to cancel and bind jquery hover events

Detailed explanation of the correct way to cancel and bind jquery hover events

黄舟
Release: 2017-06-26 13:24:43
Original
2245 people have browsed it

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"); } }); 
});
Copy after login

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'); })
Copy after login
Copy after login


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"); } }); 
});
Copy after login

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'); })
Copy after login
Copy after login

The correct way to cancel a bound hover event:

$('a').off('mouseenter').unbind('mouseleave');
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template