2014-03-25 145 views
0

我在本地存儲中有一些數據它看起來像這樣shotemup_dslfjsdlfjsdf_1395732812679 8(key,value),在我需要將這些數據發送到服務器後,如果成功,我需要從localstorage刪除1行從本地存儲刪除項目ajax

for(var i=0, len=localStorage.length; i<len; i++) { 
       var name = localStorage.key(i); 
       var score = localStorage[name]; 
       console.log(name + " " + score); 
       title = name.substring(0, name.indexOf('_')); 
       username = name.substring(name.indexOf('_') + 1, name.lastIndexOf('_')); 
       var toDelete = name; 
       if(title == "shotemup"){ 
        $.ajax({ 
         type: "POST", 
         url: "/scores", 
         data : {name : username, score : score }, 
         statusCode :{ 
          400: function() { 
           console.log("Wrong data"); 
          }, 
          200: function(){ 
           console.log(toDelete); 
          } 
         }, 

        }); 
       } 
      } 

,但是當我登錄我要刪除我有相同的行(200碼處理) 例如我在localStorage的 shotemup_123_1395733862023 8235 shotemup_2342_1395733866192 8235 shotemup_dslfjsdlfjsdf_1395732812679 8在localStorage的200碼的處理程序會記錄shotemup_dslfjsdlfjsdf_1395732812679 3次

回答

3

你可以使用removeItem()方法

for (var i = 0, len = localStorage.length; i < len; i++) { 
    //use a closure to escape the loop variable 
    (function(i){ 
     var name = localStorage.key(i); 
     var score = localStorage[name]; 
     console.log(name + " " + score); 
     title = name.substring(0, name.indexOf('_')); 
     username = name.substring(name.indexOf('_') + 1, name.lastIndexOf('_')); 
     var toDelete = name; 
     if (title == "shotemup") { 
      $.ajax({ 
       type: "POST", 
       url: "/scores", 
       data: { 
        name: username, 
        score: score 
       }, 
       statusCode: { 
        400: function() { 
         console.log("Wrong data"); 
        }, 
        200: function() { 
         console.log(toDelete); 
         //remove item with the given name 
         localStorage.removeItem(name) 
        } 
       }, 

      }); 
     } 

    })(i); 
} 
+0

哦,我看到了不同的 –

0

那麼你可以使用下面給出的這些方法: -

localStorage.removeItem('name'); 

這種方法從localStorage的去除單和顆粒項目。

localStorage.clear(); 

此方法用於copmletely清除localStorage。

相關問題