【问题标题】:Dynamic added elements double effect after page transition页面过渡后动态添加元素双重效果
【发布时间】:2013-10-30 15:39:45
【问题描述】:

我在代码中添加了来自 jQuery 的动态,但是当我返回一页并返回添加 's 的页面并按下它们时,它们现在以某种方式单击了两次。

我尝试过使用 alert('something');当我点击时:

$(document).on('click', '#products a', function() {
  alert('something');
}

当您返回页面时,它会显示两次。我试过了

$('#products a').remove();

当您单击“返回”按钮时,因为我认为所有元素都添加了两次,但这并没有什么区别。

我没有关于这些行的任何东西,也许我需要 $(document).ready();还是有pageinit的东西?

【问题讨论】:

  • 请发布您的 HTML

标签: javascript jquery html jquery-mobile


【解决方案1】:

这也称为多事件触发问题,由于其架构,它在 jQuery Mobile 中很常见。

这个问题有几种解决方案:

解决方案 1

最好的解决方案是使用 pageinit 来绑定事件。如果您查看官方文档,您会发现 pageinit 只会触发一次,就像文档准备好一样,因此无法再次绑定事件。这是最好的解决方案,因为您没有像使用 off 方法删除事件那样的处理开销。

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

这个可行的解决方案是基于之前有问题的示例。

解决方案 2

在绑定之前移除事件:

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

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

解决方案 3

使用 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 好得多。

解决方案 4

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

$(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/

可以在 here 找到工作示例。

另一件事,不要使用 jQuery Mobile 准备好的文档,而是使用适当的页面事件。最好的解决方案是使用只触发一次的 pageinit,了解更多信息here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-11
    • 2021-07-12
    • 1970-01-01
    • 2014-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-10
    相关资源
    最近更新 更多