我正在使用Ionic
,并将用户的首选项保存在localstorage中。
现在,我想在此人的个人资料中显示此数据(因此在不同的屏幕/页面中),但是我不知道如何获取此数据。
有人可以帮我吗?
// 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
最佳答案
只要您位于同一域中,就应该有权访问相同的localStorage对象。所以这应该工作:
var favorites = JSON.parse(localStorage.getItem('favorites')) || [];