【发布时间】:2015-12-25 10:14:30
【问题描述】:
我正在将一个数组保存到本地存储,然后将数组中的单词添加到我正在编写的 chrome 扩展程序中使用的 popup.html 页面上的ul。
问题是在我离开 popup.html 后,我保存到本地存储的关键字不再出现在表单中。
这让我相信我没有将它们保存到本地存储中。
我是否正确保存数组并正确调用存储在本地存储中的数组中的关键字?
keyWordArray = [];
keyWords = $('#keyWords').html();
keyWordArray = localStorage.keyWords;
keyIn = localStorage.setItem("keyWords", JSON.stringify(keyWordArray));
keyOut= JSON.parse(keyWordArray);
Description = $('#description').val();
loadKeys = function loadKeyWords() {
//clear the existing data
$('#keyWords').html('');
//for all the items in the array...
for(var i = 0; i < keyOut.length; i++) {
//add them to the UL
$('#keyWords').append('<li><input id="check" name="check" type="checkbox">'+keyWordArray[i]+'</li>');
}
};
$(document).ready(function () {
$('#add').click( function() {
if($(Description) === '') {
$('#alert').html("<strong>Warning!</strong> Enter some things you hate!");
$('#alert').fadeIn().delay(1000).fadeOut();
return false;
}
//add the new keyword to the array
keyWordArray.push(Description);
//overwrite the array in localStorage with the new, updated array
keyIn();
//call loadKeyWords() to rebuild the UL and hide any matching elements
loadKeys();
return false;
});
$('#clear').click( function() {
window.localStorage.clear();
location.reload();
return false;
});
window.addEventListener('DOMContentLoaded', function() {
var page = chrome.extension.getBackgroundPage();
// now you can access the background page objects / functions
for(var i = 0; i < keyWordArray.length; i++) {
//and hide any DOM elements that have the keyword
$("div:contains('"+keyWordArray[i]+"')").hide();
}
});
loadKeys();
}); //end of document ready function
【问题讨论】:
-
我相信 localstorage 只接受键值对,这可能是它不直接保存数组的原因。也许尝试使用
localStorage.keyWords =keyWordArray或localStorage.setItem("keyWords", keyWordArray) -
好吧,我认为你的权利从我读到的。 JS不是我最强的。您是说添加该行,它应该修复我的程序或更改我提到本地存储的任何地方?
标签: javascript arrays google-chrome-extension local-storage