In web design, we often use jquery to respond to mouse hover events, and the mouseover and mouseout events have the same effect, but how do you bind the hover method with bind? How do I unbind an event with unbind?
How to bind a hover event
First look at the following code, suppose we bind a click and hover event to the A 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 on the A tab, strange things happen, where the bound hover event is completely unresponsive, the bound click event can respond normally.
But if you put it another way, say:
$ ("a"). Hover (function () {
alert (' mouseover ');
}, Function () {
alert (' mouseout ');
})
This code can run normally, can't bind bind hover?
Instead, you should use the MouseEnter and MouseLeave events instead, which is also the event used in the. Hover () function, so you can simply refer to it 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 itself to facilitate user bindings to invoke MouseEnter and MouseLeave events, it is not a real event, so of course it cannot be invoked as an event parameter in. bind ().
Ii. How to cancel the hover event
As you know, you can use the Unbind function to unbind events, but only events bound by bind can be canceled, and the hover event in jquery is special, and if the event is bound in this way, it cannot be canceled.
$ ("a"). Hover (function () {
alert (' mouseover ');
}, Function () {
alert (' mouseout ');
})
The correct way to unbind a hover event:
$ (' a '). Unbind (' MouseEnter '). Unbind (' MouseLeave ');
Third, summary
In fact, these questions can go to the jquery official documentation, but very few people have seen, most of the tutorials on the web just explain how to use this method, to achieve the purpose, and do not have a deep understanding of why it is written?
If you have any doubts, please comment.
The above jquery cancellation and binding hover event implementation code is small series to share all the content, hope to give you a reference, but also hope that we support cloud habitat community.