Jquery 元素悬停仍然有效,即使我删除了 class 名称

Jquery element hover still work even if i remove the class name

我想在单击同一元素时基于 class 删除悬停效果。 这是代码:

<div class="myClass"> some text </div>

和Javascript:

$('.myClass').on('click', function(e) {
    $(this).removeClass('myClass');
    alert('myClass is removed from the element but the hover effect still work. i dont want that i want the hover effect to work just if the element has .myClass ');
})

这是jsfiddle

class仅用于标识bindevent的元素,即mouseentermouseleave事件。这就是为什么删除 class 没有任何作用;这是您要删除的事件。这将删除这些事件:

$(this).unbind('mouseenter mouseleave');

作为 , you can also use the optional selector for the .on() 方法的替代方法来指定触发事件的元素,如下所示:

$(document.body).on('mouseenter', '.myClass', function () {
    $(this).css('color','red');
}).on('mouseleave', '.myClass', function () {
    $(this).css('color','black');
});

$('.myClass').on('click', function(e) {
    $(this).removeClass('myClass');
    alert('myClass is removed from the element but the hover effect still work. i dont want that i want the hover effect to work just if the element has .myClass ');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="myClass"> some text </div>

虽然这更接近您认为 .hover() 方法所做的事情,但它可能会产生不良副作用。

解除绑定是一个很酷的选项,但您也可以使用 jQuery 的 .off() 功能,如下所示:

('.myClass').on('click', function(e) {

    $('.myClass').off('mouseleave mouseleave');

});

它删除了那些 mouseentermouseleave 事件的相关事件处理程序。

已更新Fiddle