簡體   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