Answers:
$(this).unbind('mouseenter').unbind('mouseleave')
或更简洁(感谢@Chad Grant):
$(this).unbind('mouseenter mouseleave')
实际上,jQuery文档比上面显示的链接示例具有更简单的方法(尽管它们可以正常工作):
$("#myElement").unbind('mouseenter mouseleave');
从jQuery 1.7开始,您还可以使用$.on()和$.off()进行事件绑定,因此要取消绑定悬停事件,可以使用更简单,更简洁的方法:
$('#myElement').off('hover');
伪事件名称“ hover” 用作 “ mouseenter mouseleave” 的简写,但在早期的jQuery版本中的处理方式有所不同;要求您明确删除每个文字事件名称。$.off()现在使用可以让您使用相同的速记来删除两个鼠标事件。
编辑2016年:
仍然是一个受欢迎的问题,因此值得在下面的注释中引起@ Dennis98的注意,即在jQuery 1.9+中,不推荐使用 “悬停”事件,而推荐使用标准的“ mouseenter mouseleave”调用。因此,您的事件绑定声明现在应如下所示:
$('#myElement').off('mouseenter mouseleave');
$.off("hover")但无法正常工作。但是,同时使用两个事件效果很好。
$.off()仍然存在,这是当前取消绑定事件的推荐方法。因此,到目前为止,您需要写$(element).off("mouseenter mouseleave");。
另一个解决方案是.die()用于与.live()关联的事件。
例如:
// attach click event for <a> tags
$('a').live('click', function(){});
// deattach click event from <a> tags
$('a').die('click');
您可以在此处找到很好的参考:探索jQuery .live()和.die()
(对不起,我的英语:“>)
悬停在后台执行的所有操作都绑定到mouseover和mouseout属性。我会分别从这些事件绑定和取消绑定您的函数。
例如,假设您有以下html:
<a href="#" class="myLink">Link</a>
那么您的jQuery将是:
$(document).ready(function() {
function mouseOver()
{
$(this).css('color', 'red');
}
function mouseOut()
{
$(this).css('color', 'blue');
}
// either of these might work
$('.myLink').hover(mouseOver, mouseOut);
$('.myLink').mouseover(mouseOver).mouseout(mouseOut);
// otherwise use this
$('.myLink').bind('mouseover', mouseOver).bind('mouseout', mouseOut);
// then to unbind
$('.myLink').click(function(e) {
e.preventDefault();
$('.myLink').unbind('mouseover', mouseOver).unbind('mouseout', mouseOut);
});
});
您可以删除通过连接一个特定的事件处理程序on,使用off
$("#ID").on ("eventName", additionalCss, handlerFunction);
// to remove the specific handler
$("#ID").off ("eventName", additionalCss, handlerFunction);
使用此方法,您将仅删除handlerFunction
另一个好的做法是为多个附加事件设置一个nameSpace
$("#ID").on ("eventName1.nameSpace", additionalCss, handlerFunction1);
$("#ID").on ("eventName2.nameSpace", additionalCss, handlerFunction2);
// ...
$("#ID").on ("eventNameN.nameSpace", additionalCss, handlerFunctionN);
// and to remove handlerFunction from 1 to N, just use this
$("#ID").off(".nameSpace");
我发现这是.hover()的第二个参数(函数)
$('#yourId').hover(
function(){
// Your code goes here
},
function(){
$(this).unbind()
}
});
第一个函数(.hover()的参数)是鼠标悬停,它将执行您的代码。第二个参数是mouseout,它将与#yourId解除绑定悬停事件。您的代码将只执行一次。
$.unbind()本身不会从该对象中删除所有事件吗?在这种情况下,您的$.click()事件之类的事情现在会失败,对吗?