Javascript 防止元素基于上一个类设置动画 $('.example')。悬停( 函数(){ $(this.css('background','red'); }, 函数(){ $(this.css('background','yellow'); } ); $('.test')。单击(函数(){ $(this.css('marginTop','+=20px').removeClass('example'); } );
尽管类Javascript 防止元素基于上一个类设置动画 $('.example')。悬停( 函数(){ $(this.css('background','red'); }, 函数(){ $(this.css('background','yellow'); } ); $('.test')。单击(函数(){ $(this.css('marginTop','+=20px').removeClass('example'); } );,javascript,jquery,Javascript,Jquery,尽管类示例似乎已被删除,但它的悬停操作仍应用于曾经拥有该类的元素。我怎样才能防止这种情况 这里是JSFIDLE。如您所见,在执行单击函数删除类后,悬停时背景仍会更改。$('.example')。解除绑定('mouseenter')。解除绑定('mouseleave') 在代码中,$('.example').hover将mouseenter和mouseleave直接附加到每个元素 -或 更好的解决方案可能是在on上使用委托 $('.example').hover( function () {
示例
似乎已被删除,但它的悬停
操作仍应用于曾经拥有该类的元素。我怎样才能防止这种情况
这里是JSFIDLE。如您所见,在执行单击
函数删除类后,悬停时背景仍会更改。$('.example')。解除绑定('mouseenter')。解除绑定('mouseleave')
在代码中,$('.example').hover
将mouseenter和mouseleave直接附加到每个元素
-或
更好的解决方案可能是在on上使用委托
$('.example').hover(
function () {
$(this).css('background','red');
},
function () {
$(this).css('background','yellow');
}
);
$('.test').click(function(){
$(this).css('marginTop','+=20px').removeClass('example');
}
);
<div class="text example"></div>
使用该代码,删除示例
类将按预期工作,因为处理程序基于css选择器,而.hover
直接附加到元素
$(document.body).on('mouseenter', '.example', function() { ... });
$(document.body).on('mouseleave', '.example', function() { ... });
演示:事件处理程序绑定到一个节点,因此该节点是否不再拥有特定的类名并不重要。您需要手动
.unbind()
这些事件,或者更好地使用jQuerys.off()
方法
所以,如果您可以确保没有任何其他事件处理程序绑定到该节点,只需调用
$('.example').live({
mouseenter:function () {
$(this).css('background','red');
},
mouseleave:function () {
$(this).css('background','yellow');
}
});
这将从该节点中删除任何事件处理程序。如果需要具体说明,可以使用jQuerys事件名称空间,如下所示
并使用此调用仅取消绑定命名空间.myNamespace
$('.example').on( 'mouseenter.myNamespace'
function () {
$(this).css('background','red');
}
).on('mouseleave.myNamespace'
function() {
$(this).css('background','yellow');
}
);
试试这个:
$(this).css('marginTop','+=20px').removeClass('example').off('.myNamespace');
或者干脆。解开('mouseenter mouseleave')
$(this).css('marginTop','+=20px').removeClass('example').off('.myNamespace');
$('.test').hover(
function () {
$('.example').css('background','red');
},
function () {
$('.example').css('background','yellow');
}
);