页面转换后动态添加元素双重效果

时间:2013-10-30 15:39:45

标签: javascript jquery html jquery-mobile

我已经在我的代码中添加了jQuery的动态,但是当我返回一个页面并返回添加了它们的页面并按下它们时,它们会以某种方式点击两次。

我尝试过警告('某事');当我点击:

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

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

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

单击“后退”按钮时,因为我认为所有元素都添加了两次,但没有区别。

这些线路周围没有任何东西,也许我需要$(document).ready();或者有关于pageinit的东西?

1 个答案:

答案 0 :(得分:3)

这也称为多事件触发问题,由于其架构,它在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 Filter选择器,如下所示:

$('#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