0

在 localStorage 我有一个对象记录。它有很多字段记录[recordId],我希望能够删除这些条目。下面是我的删除功能,但它不起作用。所有记录仍然附加到本地存储中的记录对象。不知道出了什么问题,因为我正在以正确的方式删除。当我打印记录对象时,所有记录及其键仍然存在????

function deleteLocalRecord(recordId) {
     var records = localStorage.getItem('records');
     var theRecords;
     if (supports_html5_storage()) {

          if (records == null) {
            theRecords = {};
          } else {
            // parse the records
            theRecords = JSON.parse(records);
          }

          theRecords[recordId] = '';  // set the record to empty string.
          delete theRecords[recordId]; // delete the record

          // reset the records object in local storage after change
          localStorage.setItem('records', JSON.stringify(theRecords));

     }
  }

  function supports_html5_storage() 
  {
    try 
    {
        return 'localStorage' in window && window['localStorage'] !== null;
    } 
    catch (e) 
    {
        return false;
    }
   }
4

1 回答 1

0

现场演示

function deleteLocalRecord(recordId) {
    if (localStorageEnabled()) {
        var records = localStorage.getItem('records'),
            theRecords  = JSON.parse(records) || {};

        print(JSON.stringify(theRecords)); // before
        delete theRecords[recordId]; // delete
        print(JSON.stringify(theRecords)); // after

        localStorage.setItem('records', JSON.stringify(theRecords));
        print(localStorage.getItem("records"));
    }
}

var records = {
    "test": "test",
    "stuff": "stuff"
};

localStorage.setItem("records", JSON.stringify(records));
deleteLocalRecord("test");


function print(x) {
    document.body.innerHTML += "<p>" + x + "</p>";
};

function localStorageEnabled() {
    return typeof window["localStorage"] !== "undefined";
};
于 2013-05-30T15:13:23.707 回答