3
$('.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>

尽管该类example似乎已被删除,但hover它的操作仍在应用于曾经拥有该类的元素。我怎样才能防止这种情况?

http://jsfiddle.net/gSfc3/

这是在 jsFiddle 中。如您所见,在执行click删除类的函数后,悬停时背景仍然会发生变化。

4

4 回答 4

1

事件处理程序绑定到Node,因此该 Node 是否不再拥有特定的 className 并不重要。您需要.unbind()手动处理这些事件,或者更好的是,使用 jQuerys.off()方法。

因此,如果您可以确定没有任何其他事件处理程序绑定到该节点,只需调用

$(this).css('marginTop','+=20px').removeClass('example').off();

这将从该节点中删除任何事件处理程序。如果需要具体,可以使用 jQuerys Event 命名空间,像这样

$('.example').on( 'mouseenter.myNamespace'
   function () {
       $(this).css('background','red');
   }
).on('mouseleave.myNamespace'
   function() {
       $(this).css('background','yellow');
   }
);

并使用此调用仅取消绑定命名空间内的任何事件.myNamespace

$(this).css('marginTop','+=20px').removeClass('example').off('.myNamespace');
于 2012-04-24T18:28:47.260 回答
0

尝试这个:

$('.test').hover(
    function () {
        $('.example').css('background','red');
    },
    function () {
        $('.example').css('background','yellow');
    }
);
于 2012-04-24T18:32:12.733 回答
0

$('.example').unbind('mouseenter').unbind('mouseleave')

在您的代码中,$('.example').hover将 mouseenter 和 mouseleave 直接附加到每个元素。

-或者-

更好的解决方案可能是使用委托on

$(document.body).on('mouseenter', '.example', function() { ... });
$(document.body).on('mouseleave', '.example', function() { ... });

使用该代码,删除example类将按预期工作,因为处理程序基于 css 选择器,同时.hover直接附加到元素。

于 2012-04-24T18:27:22.253 回答
0
$('.example').live({
    mouseenter:function () {
        $(this).css('background','red');
    },
    mouseleave:function () {
        $(this).css('background','yellow');
    }
});

演示:http: //jsfiddle.net/gSfc3/1/

于 2012-04-24T18:28:21.583 回答