2013-05-30 70 views
0

在localStorage中我有一個對象記錄。它有很多字段 records [recordId],我希望能夠刪除這些條目。下面是我的刪除功能,但它不起作用。所有記錄都保留附加到本地存儲中的記錄對象。不知道什麼是錯誤的,因爲我正在以正確的方式刪除。當我打印記錄對象時,所有記錄都與它們的鍵一起還在那裏?如何刪除存儲在localStorage中的對象的屬性?

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; 
    } 
    } 
+1

你有一個全局變量'surveys'在那裏,一個功能'supports_html5_storage'太...我懷疑任何人都可以不知道他們是什麼幫助。 – Dancrumb

+0

'supports_html5_storage()'這個函數裏面有什麼?如果它返回false,那麼這個函數將不會執行任何操作。 –

+0

對不起,我上面更新。支持本地存儲只是支持本地存儲的檢查。代碼肯定會運行。但我注意到,我無法設置與刪除行斷點。 – Javascripter

回答

-1

Live demo

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"; 
}; 
+0

是的,這確實運行正確,在我的案例中,記錄看起來更像:「testt」:「{t1:t1val,t2:t2Val}」不確定這是否是差異。 – Javascripter

+0

好的。它確實有效。問題是我循環並調用deleteLocalRecord之後重置了Records。 – Javascripter

相關問題