将阵列保存到Chrome本地存储

时间:2015-12-25 00:45:25

标签: javascript arrays google-chrome-extension local-storage

我正在将数组保存到本地存储,然后将数组中的单词添加到我正在编写的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

2 个答案:

答案 0 :(得分:2)

这是一个解决方案,它超出了您的问题,将数组显式保存到本地存储:

// set up the array
var theArray = ['red', 'green', 'blue'],
    localStorageTheArray;

// convert the array to a string and write it to local storage 
localStorage.setItem('theArray', JSON.stringify(theArray));

// retrieve the string from local storage and convert it back to an array
localStorageTheArray = JSON.parse(localStorage.getItem('theArray'));

localStorageTheArray.push('purple');

console.log(localStorageTheArray);
// ["red", "green", "blue", "purple"]

链接到JS Fiddle

功能示例

function setArrayInLocalStorage(key, array) {
    localStorage.setItem(key, JSON.stringify(array));
}

function getArrayInLocalStorage(key) {
    return JSON.parse(localStorage.getItem(key));
}

// to set
setArrayInLocalStorage('theArray', theArray);

// to get
getArrayInLocalStorage('theArray');

答案 1 :(得分:0)

替换

localStorage["keyWords"] = JSON.stringify(keyWordArray);

使用:

localStorage.setItem("keyWords", JSON.stringify(keyWordArray));

然后在访问关键字时使用:

localStorage.keyWords

而不是:

localStorage["keyWords"]

无法保证能够解决您的所有问题,但它应解决本地存储问题。