In web design, we often use jquery to respond to mouse hover events, and mouseover and mouseout events have the same effect, but how do you use on to bind the hover method? How do I unbind an event with off?
First, how to bind the hover event
Let's look at the following code, assuming 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 you click on the a tag, something strange happens, where the bound hover event is completely unresponsive, and the bound click event responds normally.
But if you change the wording, for example:
$ ("a"). Hover (function () {alert (' mouseover ');}, function () {
Alert (' mouseout '); })
The two events, MouseEnter and MouseLeave, should be used instead, (this is also the event used in the. Hover () function)
So you can simply refer to 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) {
/ /Click event handler
Alert ("click"); } });
});
Because. Hover () is a jquery-defined event that is designed to make it easier for users to bind calls to MouseEnter and MouseLeave events, which is not a real event, so of course it cannot be called as an event argument in. On ().
Second, how to cancel the hover event
As you know, you can use the off function to unbind an event, but only the events bound by bind are canceled, and the hover event in jquery is quite special and cannot be canceled if the event is bound in this way.
$ ("a"). Hover (function () {alert (' mouseover ');}, function () {
Alert (' mouseout '); })
The correct way to unbind the hover event:
$ (' a '). Off (' MouseEnter '). Unbind (' MouseLeave ');
The correct way to cancel and bind hover events in jquery