【问题标题】:jQueryMobile Dynamic Pages - Events triggered multiple timesjQueryMobile 动态页面 - 事件多次触发
【发布时间】:2013-12-04 20:19:48
【问题描述】:

我正在开发一个让人们订购产品的 jQueryMobile 网站。有动态页面(例如产品页面),我有一些事件(计算总数,刷新成分列表等)。

您第一次进入产品页面时一切正常,但是在您将产品添加到购物车并返回另一个产品后,一切都会再次触发。因此,例如,如果您在购物车中添加 10 件商品,那么对于第 10 件商品,所有内容(包括 ajax 调用)都会被触发 10 次。

我在这里录制了一段视频:http://www.screenr.com/Ew5H,这样您就可以准确地看到问题所在。

网址为:http://m2.pizzaboy.y11.in/

JS文件在这里:http://m2.pizzaboy.y11.in/assets/js/main.js

我正在使用:

$( document ).delegate("#page-product", "pageinit", function() {
    //stuff here
});

触发产品页面上的所有操作。

我尝试了各种解决方案来解决这个问题(删除不再活动的页面元素,使用标志等),但没有任何效果。

感谢您的帮助

【问题讨论】:

  • 您在添加产品后删除页面?如果是,那么您必须在将页面产品留在pagehidepagebeforehide 事件上时取消绑定所有change 事件。 $(document).on("pagehide", "#page_id", function () { $(document).off("change", "selectors"); }); }); 因为每当启动同一页面 #page-product 时,它都会添加 change 侦听器。
  • 感谢您的评论@Omar,但它似乎无法解决问题。还有其他想法吗?
  • 另外注意,使用.on 而不是.delegate。没有页面叫page-product?
  • #page-product 存在,在参数顺序旁边使用.on.delegate 没有区别,因此使用.on 也不能修复它..
  • 在页面隐藏尝试$('selectors').off('change click')

标签: javascript jquery jquery-mobile navigation


【解决方案1】:

解决方案确实是解除绑定事件(使用.off),但是如果您提供多个选择器,.off 不起作用(至少对我而言)。

例子:

// This is NOT WORKING because multiple elements are used
$(document).off('change', '.class1, .class2, #idelement');

// This WORKS
$(document).off('change','#idelement');
$(document).off('change','.class1');
// and so on...

// You can add a class to all elements that you want to
// unbind, and then just call it once
$(document).off('event','.classForUnbind')

// If you want to unbind all elements
$(document).off('change');

希望对你有帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-07
    • 1970-01-01
    • 2012-10-09
    • 2015-05-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多