簡體   English   中英

使用localStorage顯示最近訪問的n頁

[英]Use localStorage to display the last n pages visited

我想最多捕獲訪問的最后3頁,並存儲url和其他字符串數據,例如標題和描述。

本地存儲似乎是最好的選擇,但是我應該使用哪種方法保存數據?

如果我創建一個數組,我會看到如何將其作為對象推送

var testObject = { 'url': window.location.href, 'location': 'Japan', 'desc': 'some brief description text' };
localStorage.setItem('testObject', JSON.stringify(testObject));

但是,如何在localStorage中存儲/更新(在此示例中)這些陣列中的最新3個,然后按上次訪問的順序檢索所有3個以在頁面上列出?

您可以利用內置的shiftpush方法:

  • shift :從數組中刪除最后一個元素
  • push :它將一個或多個元素添加到數組的末尾

第一次請求頁面時,將對象保存在數組中並將其放置在localStorage

var items = [{ 'url': window.location.href, 'location': 'Japan', 'desc': 'some brief description text' }];
localStorage.setItem('testObject', JSON.stringify(items));

在正在進行的通話中,測試數組的length並相應地shiftpush新項:

var items = JSON.parse(localStorage.getItem('testObject'));
if(items.length === 3) {
  items.shift(); //the first item in the array is removed. So length is 2
}

items.push(your new item); //length is 3 

最后將新項目保存到存儲中:

localStorage.setItem('testObject', JSON.stringify(items));

您可以創建一個find方法來查找您需要使用的內容:

var find = function(arr, url) {
  return arr.filter(function(el) {
    return el.url === url;
  })[0];
}

var item = find(items, 'http://url.com');

請注意, localStorageECMAScript 5th Edition的一部分。 因此,為不支持它的瀏覽器提供一個polyfill。 如果需要跨瀏覽器的兼容性,請確保同時存在shift和push(盡管是非常標准的方法)。

有關陣列的更多信息,請參見Mozilla MDN:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM