【问题标题】:unbind not work in JQuery Mobile取消绑定在 JQuery Mobile 中不起作用
【发布时间】:2013-04-16 07:15:40
【问题描述】:

这是我的代码:

$("#infoButton").unbind('click');
                $("#infoButton").click(
                    function(event) {
                        try {
                            bla bla bla....
                        } catch (e) {
                            alert(e);
                        }
                    }
                );

我发现那个事件已经解除了所有事件的绑定,但是“bla bla bla”还在累积!

事件不能解除绑定。

jQuery 版本 1.8.2

【问题讨论】:

  • 将取消绑定移到绑定下方?

标签: jquery-mobile jquery-plugins jquery


【解决方案1】:

防止多个事件绑定/触发

由于有趣的 jQM 加载架构,多事件触发一直是个问题。例如,看看这段代码:

$(document).on('pagebeforeshow','#index' ,function(e,data){    
    $(document).on('click', '#test-button',function(e) {
        alert('Button click');
    });    
});

工作 jsFiddle 示例:http://jsfiddle.net/Gajotres/CCfL4/

每次访问页面#index点击事件都会绑定到按钮#test-button。有几种方法可以防止此问题:

解决方案 1:

在这种情况下,您应该使用函数 on 而不是 bind。它更快 并打算替换绑定和委托。

在绑定之前移除事件:

$(document).on('pagebeforeshow','#index',function(e,data){    
    $(document).off('click', '#test-button').on('click', '#test-button',function(e) {
        alert('Button click');
    });    
});

工作 jsFiddle 示例:http://jsfiddle.net/Gajotres/K8YmG/

如果你有不同的事件绑定到一个对象:

$('#index').on('pagebeforeshow',function(e,data){    
    $(document).off('click tap', '#test-button').on('click tap', '#test-button',function(e) {
        alert('Button click');
    });    
});

解决方案 2:

使用 jQuery 过滤器选择器,如下所示:

$('#carousel div:Event(!click)').each(function(){
    //If click is not bind to #carousel div do something
});

因为事件过滤器不是官方 jQuery 框架的一部分,所以可以在这里找到:http://www.codenothing.com/archives/2009/event-filter/

简而言之,如果您主要关心的是速度,那么解决方案 2 比解决方案 1 好得多。

解决方案 3:

一个新的,可能是其中最简单的一个。

$(document).on('pagebeforeshow', '#index', function(){       
    $(document).on('click', '#test-button',function(e) {
        if(e.handled !== true) // This will prevent event triggering more then once
        {
            alert('Clicked');
            event.handled = true;
        }
    }); 
});

工作 jsfiddle 示例:http://jsfiddle.net/Gajotres/Yerv9/

此解决方案的 Tnx 至 [sholsinger][2]:http://sholsinger.com/archive/2011/08/prevent-jquery-live-handlers-from-firing-multiple-times/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-15
    • 2012-05-10
    • 2013-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多