jquery中取消和绑定hover事件的正确方式

在网页设计中,我们经常使用jquery去响应鼠标的hover事件,和mouseover和mouseout事件有相同的效果,但是这其中其中如何使用bind去绑定hover方法呢?如何用unbind取消绑定的事件呢?
一、如何绑定hover事件
先看以下代码,假设我们给a标签绑定一个click和hover事件:
$(document).ready(function(){ $('a').bind({ hover: function(e) { //
Hover event handler alert("hover"); }, click: function(e) { // Click
event handler alert("click"); } }); });
当点击a标签的时候,奇怪的事情发生了,其中绑定的hover事件完全没有反应,绑定的click事件却可以正常响应。

但是如果换一种写法,比如:
$("a").hover(function(){ alert('mouseover'); }, function(){
alert('mouseout'); })
这段代码就可以正常的运行,难道bind不能绑定hover?

其实不是,应该使用 mouseenter 和 mouseleave 这两个事件来代替,(这也是 .hover() 函数中使用的事件)
所以完全可以直接像这样来引用:
$(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"); } }); });
因为.hover()是jQuery自己定义的事件,是为了方便用户绑定调用mouseenter和mouseleave事件而已,它并非一个真正的事件,所以当然不能当做.bind()中的事件参数来调用。
二、如何取消hover事件
大家都知道,可以使用unbind函数去取消绑定的事件,但是只能取消通过bind绑定的事件,jquery中的hover事件是比较特殊的,如果通过这种方式去绑定的事件,则无法取消。
$("a").hover(function(){ alert('mouseover'); }, function(){
alert('mouseout'); })
取消绑定的hover事件的正确方式:
$('a').unbind('mouseenter').unbind('mouseleave');三、总结
其实,这些问题可以去参看jquery官方的说明文档,只是很少有人去看过,网上的大多数教程只是讲解如何去使用这个方法,达到目的即止,并没有深入的了解为什么这么写?

如果你有什么疑惑,欢迎评论留言。


原文链接:http://www.uedsc.com/jquery-bind-hover-event.html

原文地址:https://www.cnblogs.com/0to9/p/5451860.html