Implementation Code for canceling and binding hover events in jquery, jqueryhover
In web design, jquery is often used to respond to hover events of the mouse, which has the same effect as mouseover and mouseout events. But how can we bind a hover event to the bind method? How to Use unbind to cancel binding events?
I. How to bind a hover event
Let's look at the following code first. Suppose we bind a click and hover event to the tag:
$(document).ready(function(){ $('a').bind({ hover: function(e) { // Hover event handler alert("hover"); }, click: function(e) { // Click event handler alert("click"); } });});
When you click the tag, a strange thing happens. The bound hover event does not respond at all, but the bound click event can respond normally.
However, if you use another method, for example:
$("a").hover(function(){ alert('mouseover');}, function(){ alert('mouseout');})
This code can run normally. Can't bind be bound to hover?
Actually not. You should use the mouseenter and mouseleave events instead. (this is also the event used in the. hover () function), so it can be referenced directly like this:
$(document).ready(function(){ $('a').bind({ mouseenter: function(e) { // Hover event handler alert("mouseover"); }, mouseleave: function(e) { // Hover event handler alert("mouseout"); }, click: function(e) { // Click event handler alert("click"); } });});
Because. hover () is an event defined by jQuery. It is used to facilitate binding and calling of mouseenter and mouseleave events. It is not a real event, so it cannot be considered as. bind.
Ii. How to cancel a hover event
As we all know, you can use the unbind function to unbind events, but you can only cancel events bound by bind. hover events in jquery are special. If you bind events in this way, cannot be canceled.
$("a").hover(function(){ alert('mouseover');}, function(){ alert('mouseout');})
The correct method for unbinding hover events is as follows:
$('a').unbind('mouseenter').unbind('mouseleave');
Iii. Summary
In fact, you can refer to the official instructions of jquery for these questions, but few have read them. Most of the tutorials on the Internet only explain how to use this method, I did not have a deep understanding of why I wrote this?
If you have any questions, please leave a comment.
The implementation code for canceling and binding hover events in jquery above is all the content shared by the editor. I hope you can give us a reference and support the house of helpers.