繁体   English   中英

jquery bbq - 检测用户点击后退按钮的时间

[英]jquery bbq - detect when user clicks back button

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

  • 其中一个页面“#catalogue”包括一个项目网格,这些项目使用函数“randomItems()”随机生成,在hashchange上触发(来自另一个页面时)。
  • 然后,用户单击网格中的任何这些项目以查看#details页面
  • 单击浏览器后退按钮,我希望用户查看#catalogue页面(工作正常)但是阻止页面生成一组新的随机项目onload(所以保留上次显示的任何项目)。

有没有办法知道用户已经按下后退按钮,所以在这种情况下我不会触发“randomItems()”函数?

您需要将来自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
});

使用浏览器的本地存储来保存项目。 首先创建对象的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.html在HTML5 localStorage中存储对象

相信bbq允许你设置和获取url参数,你可以用这些来确定你是否需要随机。 当用户点击链接到目录时,网址就像:

http://yoururl.com/#catalog

所以这是目录的“根”网址,每当网址是你随机化的项目,随机化项目后你将一个参数添加到网址,所以它变成了:

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
}

而不是urlParamIsSet/urlSetParam使用bbq提供的任何函数来操作url。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM