【问题标题】:jquery bbq - detect when user clicks back buttonjquery bbq - 检测用户何时单击后退按钮
【发布时间】:2013-05-16 16:05:12
【问题描述】:

我已经成功实现了 jQuery BBQ 插件来构建一个快速原型,但是我遇到了一个与我的特定设置相关的小问题:

  • 其中一个页面 "#catalogue" 包含一个使用函数 "randomItems()" 随机生成的项目网格,该函数在 hashchange (当来自另一个页面时)。
  • 然后用户单击网格中的任何这些项目以查看 #detailspage
  • 点击浏览器后退按钮后,我希望用户查看 #catalogue 页面(工作正常)但阻止页面生成一组新的随机加载项(所以保留最后显示的所有项目)。

有没有办法知道用户点击了返回按钮,所以在这种情况下我不会触发 "randomItems()" 函数?

【问题讨论】:

    标签: jquery browser-history hashchange jquery-bbq


    【解决方案1】:

    您需要将来自randomItems() 的项目放入缓存中:

    // save your records here in the cache
    var items = [];
    
    $(window).on('hashchange', function(){
        var page = window.location.hash.replace(/^#/, '');
    
        // check first if items has already records in it and check if page is #catalogue
        // if not then call randomItems()
        if (page === 'catalogue' && items.length === 0) {
            items = randomItems();
        }
    
        // your code here follows
    });
    

    【讨论】:

    • 感谢您的快速回复。不幸的是,这样做会阻止原型的其他区域工作。在 #catalogue 页面中,用户可以点击另一个菜单链接,这需要生成一组新的随机项目。如果我使用您的解决方案,一旦我进入目录,我就无法更改其内容。不知何故,如果可能的话,它需要全部使用后退按钮:)
    • @ale 编辑了我的答案。我添加了一个条件,只有当页面是#catalogue时才会发生缓存
    • 不幸的是,问题仍然存在,因为从#detailspage 中,您可以单击菜单上的某些内容并触发目录的新实例,但只能使用新的随机项目..
    • 看了你的建议后,我认为解决方案是避免加载随机项onload,并且仅在用户实际单击菜单项时触发该功能。这样浏览器的后退按钮就不会触发它。
    【解决方案2】:

    使用浏览器的本地存储来保存项目。首先创建对象的 javascript 表示。然后将其存储在 localStorage 中。在页面加载时检索。请注意,您必须对复杂对象进行字符串化才能存储它,因为存储只接受键值对

    这是一个通用模式

    var foo;
    window.onpageload = function(){
       if(localStorage["foo"] == '' | localStorage["foo"] == undefined){
         foo = getrandomItems(); //possibly an ajax call;
         localStorage["foo"] = JSON.stringify(foo);
       else{
         foo = JSON.parse(localStorage["foo"]);
       }
    };
    

    详见http://diveintohtml5.info/storage.htmlStoring Objects in HTML5 localStorage

    【讨论】:

      【解决方案3】:

      Believe bbq 允许您设置和获取 url 参数,您可以使用这些参数来确定是否需要随机化。当用户单击目录链接时,URL 类似于:

      http://yoururl.com/#catalog
      

      所以这是目录的“根”网址,只要网址是这个,你就可以随机化项目,在随机化项目后,你会在 url 中添加一个参数,这样它就变成了:

      http://yoururl.com/#catalog?r=1
      

      这样,当用户离开并查看一个项目,然后点击返回历史 url 将包含 r=1,因此您不会处理随机函数。

      function randomiseItems()
      {
        // we do not want to randomise
        if(urlParamIsSet("r")) return; 
      
        // set url param so gets stored in history (replacing current url)
        urlSetParam("r",1); 
      
        //-- do your code here
      }
      

      使用 bbq 为您提供的任何功能来操作 url,而不是 urlParamIsSet/urlSetParam

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-10-29
        • 2018-12-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多