[英]How do I unbind “hover” in jQuery?
如何在jQuery中取消绑定“悬停”?
这不起作用:
$(this).unbind('hover');
$(this).unbind('mouseenter').unbind('mouseleave')
或者更简洁(感谢@Chad Grant ):
$(this).unbind('mouseenter mouseleave')
实际上, jQuery文档比上面显示的链接示例有更简单的方法(尽管它们可以正常工作):
$("#myElement").unbind('mouseenter mouseleave');
在jQuery 1.7中,你还可以使用$.on()
和$.off()
事件的结合,所以要取消绑定悬停事件,你可以使用简单,整洁的:
$('#myElement').off('hover');
伪事件名称“悬停” 用作 “mouseenter mouseleave” 的简写 ,但在早期的jQuery版本中处理不同; 要求您明确删除每个文字事件名称。 使用$.off()
现在允许您使用相同的速记删除两个鼠标事件。
编辑2016:
仍然是一个受欢迎的问题,所以值得注意@ Dennis98在下面的评论中的观点,在jQuery 1.9+中,“悬停”事件被弃用 ,支持标准的“mouseenter mouseleave”调用。 所以你的事件绑定声明现在应该是这样的:
$('#myElement').off('mouseenter mouseleave');
单独取消绑定mouseenter
和mouseleave
事件,或取消绑定元素上的所有事件。
$(this).unbind('mouseenter').unbind('mouseleave');
要么
$(this).unbind(); // assuming you have no other handlers you want to keep
unbind()不适用于硬编码的内联事件。
因此,例如,如果你想从<div id="some_div" onmouseover="do_something();">
取消绑定鼠标悬停事件,我发现$('#some_div').attr('onmouseover','')
是一种快速而肮脏的方式来实现它。
另一个解决方案是.die()用于附加.live()的事件。
例:
// attach click event for <a> tags
$('a').live('click', function(){});
// deattach click event from <a> tags
$('a').die('click');
你可以在这里找到一个很好的参考: 探索jQuery .live()和.die()
(抱歉我的英文:“>)
您可以使用off
删除on
附加的特定事件处理程序
$("#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");
所有悬停在幕后都是绑定到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);
});
});
我发现这可以作为.hover()的第二个参数(函数)
$('#yourId').hover(
function(){
// Your code goes here
},
function(){
$(this).unbind()
}
});
第一个函数(.hover()的参数)是mouseover并将执行您的代码。 第二个参数是mouseout,它将解除悬停事件与#yourId的绑定。 您的代码只会执行一次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.