【问题标题】:jQuery mobile listview multiple click eventjQuery mobile listview 多次点击事件
【发布时间】:2013-05-21 14:46:49
【问题描述】:

我动态填写列表,然后点击我有多个事件调用。第一次重复1次,第二次重复2次,第三次重复3次,等等......

【问题讨论】:

  • 您的问题是什么?你能展示你的代码吗?
  • 显示您的代码,确保您在其他处理程序中绑定事件
  • 代码被分类,触发了事件,但是当我打开页面第2次或第3次时,触发了2次或3次事件。
  • 那么有人如何帮助您处理您在问题中发布的不相关信息?

标签: jquery-mobile jquery jquery-mobile-listview


【解决方案1】:

首先,关于这个问题的更多信息可以在我的另一个答案中找到:jQuery Mobile: document ready vs page events

防止多个事件绑定/触发

由于有趣的 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:

在绑定之前移除事件:

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

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

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

$('#index').live('pagebeforeshow',function(e,data){    
    $('#test-button').die('click').live('click', 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');
            e.handled = true;
        }
    }); 
});

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

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

更多信息

如果您想了解有关此问题的更多信息,请查看此 article,其中包含工作示例。

【讨论】:

  • 为您的外部事件处理程序使用不同的事件怎么样? pageinit 应该可以工作。这样内部事件处理程序只会绑定在新的 DOM 元素上。这已经回答过很多次了,我认为 SA 社区应该链接到现有的答案,而不是重新编写它们。另外,欢迎加入 1K jQuery Mobile 俱乐部 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-20
  • 1970-01-01
  • 1970-01-01
  • 2020-05-21
  • 1970-01-01
  • 2012-02-26
相关资源
最近更新 更多