【问题标题】:Removing class from div doesn't stop jquery function从 div 中删除类不会停止 jquery 函数
【发布时间】:2011-12-21 01:49:06
【问题描述】:

我有一个“项目”类的 div。当我在 div 上使用 .removeClass('item') 时,它不会阻止它的 jquery 函数运行。这是我的代码:

<div class = "item">
   //stuff in here
</div>

还有 jquery:

$(".item").mouseenter(function() {
   $(this).find(".clear").show();
});
$(".clear").click(function() {
   $(this).closest("div").removeClass('item');
});

当我删除它的类时(并且我成功地删除了它,我用一些 css 对其进行了测试)它仍然响应 jquery 代码。我怎样才能使它不会响应该代码?

【问题讨论】:

    标签: jquery


    【解决方案1】:

    您需要unbind() 事件处理程序。

    使用

    $(this).closest("div").removeClass('item').unbind('mouseenter');
    

    或者,您可以将初始事件绑定到容器元素(document)并将处理委托给它。这样,一旦类被删除,它确实不会对点击做出反应。

    使用 1.7 方法

    $(document).on('mouseenter','.item',function() {
       $(this).find(".clear").show();
    });
    

    使用 1.6 及以下的方法

    $(document).delegate('.item','mouseenter', function() {
       $(this).find(".clear").show();
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-21
      • 2015-12-20
      • 1970-01-01
      • 1970-01-01
      • 2014-10-25
      • 2014-08-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多