我试图在单击切换按钮时取消绑定mouseleave事件
$('.togglebutton').on('click', function () {
if ($("#navbar-main").css('margin-left') == '0px') {
$("#navbar-main").css("margin-left", "-230px");
$("#navbar-main").bind('mouseleave');
}
else{
$("#navbar-main").css("margin-left", "0px");
$("#navbar-main").unbind('mouseleave');
}
同一时间
$("#navbar-main").mouseover(function () {
$("#navbar-main").css("margin-left", "0px");
}
});
$("#navbar-main").mouseleave(function () {
$("#navbar-main").css("margin-left", "-230px");
}
});
取消绑定我正确发生但无法重新绑定mouseleave事件!
答案 0 :(得分:1)
将您的mouseenter / mouseleave calbacks移动到函数并使用' on'绑定事件。功能。当你打电话'解开'' - 在第二个参数中传递来自' on',如果你想重新绑定它 - 再次打电话' on'与calback parametr。
我使用toogle按钮创建简单的绑定 - 取消绑定示例:
<!DOCTYPE html>
<!--
Created using JS Bin
http://jsbin.com
Copyright (c) 2017 by dasiekjs (http://jsbin.com/xedibob/4/edit)
Released under the MIT license: http://jsbin.mit-license.org
-->
<meta name="robots" content="noindex">
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<button>Click to unbind</button>
<div id="test">its test!</div>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script>
var isBinding = true;
var onDivEnter = function(event){
$(event.target).text("MouseEnter");
};
var onDivExit = function(event){
$(event.target).text("MouseExit");
}
var changeEvent = function(event){
if(isBinding){
$('#test').unbind('mouseenter',onDivEnter);
$('button').text('click to bind');
} else {
$('#test').bind('mouseenter',onDivEnter);
$('button').text('click to unbind');
}
isBinding = !isBinding;
}
var rebindButton = function(event){
$('#test').bind('mouseenter',onDivEnter);
}
$("#test").on('mouseenter',onDivEnter);
$("#test").on('mouseleave',onDivExit);
$('button').on('click',changeEvent);
</script>
</body>
</html>