【问题标题】:Jquery mobile swipe left fires twiceJquery mobile向左滑动两次
【发布时间】:2023-03-10 07:57:01
【问题描述】:

我有一个非常简单的用例。

在页面初始化时加载一个 html。

 $(document).on('pageinit',function(){
                window.localStorage.setItem("page",'intro_1');                              
                $('#navigation_main').load('html/intro_1.html');

            });

在滑动时只需更改 dom。

 var flag = 0;
              $("body").bind("swipeleft",function(event) {
                flag +=1;                               
                page = window.localStorage.getItem("page"); 
                alert(flag);            
                switch(page){
                    case 'intro_1':                         
                        window.localStorage.setItem("page",'intro_2');
                        $('#navigation_main').load('html/intro_2.html');                        
                        break;  

                    case 'intro_2':
                        window.localStorage.setItem("page",'challenges');
                        $('#navigation_main').load('html/challenges.html');                     
                        break;  

                    case 'challenges':
                        window.localStorage.setItem("page",'risk_areas');
                        $('#navigation_main').load('html/risk_areas.html');                     
                        break;

                    default:
                        window.localStorage.setItem("page",'intro_1');                              
                        $('#navigation_main').load('html/intro_1.html');
                        break;  
                }

            });

现在这个向左滑动被触发了两次,导致后续页面被加载。我怎样才能阻止这种情况?

【问题讨论】:

    标签: jquery cordova jquery-mobile swipe


    【解决方案1】:

    您可以尝试使用$("body").one 而不是$("body").bind,这样它只会被调用一次。

    【讨论】:

    • 必须绑定两次试试 $("body").die("swipeleft", );这样会杀死第一个绑定的项目,然后添加它。
    • 这个答案很旧,但你的意思是$("body").on。那是“on”,而不是“one”。
    【解决方案2】:

    我假设您已经多次绑定事件,它可以通过几种方式解决。

    1. 在绑定事件之前使用 $(body).unbind();。 Unbind 将删除所有已绑定的事件。不幸的是,这不是一个好的预防措施,因为您不断地绑定/解除绑定,从而导致大量处理开销。

    2. 除了使用事件绑定/取消绑定、live/die 和 on/off 之外,还有另一种方法。不要在再次绑定之前取消绑定,而是使用 jQuery 事件过滤器,它可以用来识别事件是否已经被绑定。不要忘记从下面发布的链接下载它(它不是 jQM 的标准部分)。

      http://www.codenothing.com/archives/2009/event-filter/

      这是我的用法示例:

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

      我使用每个是因为我的轮播 div 有许多内部块,但原理是相同的。如果#carousel 内部 div 元素没有点击事件,则添加该事件。在您的情况下,这将防止多个事件绑定。

    【讨论】:

      猜你喜欢
      • 2013-10-27
      • 1970-01-01
      • 1970-01-01
      • 2011-08-25
      • 2014-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-11
      相关资源
      最近更新 更多