如何在不同的屏幕中获取本地存储数据?

时间:2018-09-12 09:02:51

标签: javascript angular ionic-framework local-storage angular-local-storage

我正在使用Ionic,并将用户的首选项保存在本地存储中。

现在,我想在此人的个人资料中显示此数据(因此在不同的屏幕/页面中),但是我不知道如何获取此数据。

有人可以帮我吗?

// get favorites from local storage or empty array
var favorites = JSON.parse(localStorage.getItem('favorites')) || [];
// add class 'fav' to each favorite
favorites.forEach(function(favorite) {
  document.getElementById(favorite).className = 'fav';
});
// register click event listener
document.querySelector('.list').addEventListener('click', function(e) {
  var id = e.target.id,
      item = e.target,
      index = favorites.indexOf(id);
  // return if target doesn't have an id (shouldn't happen)
  if (!id) return;
  // item is not favorite
  if (index == -1) {
    favorites.push(id);
    item.className = 'fav';
  // item is already favorite
  } else {
    favorites.splice(index, 1);
    item.className = '';
  }
  // store array in local storage
  localStorage.setItem('favorites', JSON.stringify(favorites));
});

// local storage stores strings so we use JSON to stringify for storage and parse to get out of storage

这是我的Codepen: https://codepen.io/CrocoDillon/pen/pIlKB

2 个答案:

答案 0 :(得分:1)

只要您位于同一域上,就应该有权访问相同的localStorage对象。所以这应该工作:

var favorites = JSON.parse(localStorage.getItem('favorites')) || [];

答案 1 :(得分:0)

const favorites = JSON.parse(localStorage.getItem('favorites')) || [];

localStorage.getItem('favorites')本身是访问者

相关问题