2014-10-07 35 views
0

我正在製作一個應用程序,記錄您在工作中獲得的小時數以及您製作的數量。 現在我這樣做:如何在創建Phonegap應用程序時添加列表項並將其保存到本地存儲?

localStorage.cachedPay = madeamount.toFixed(2); 
localStorage.cachedHours = houramount; 
$madeamount.html(localStorage.cachedPay); 
$houramount.html(localStorage.cachedHours); 

因此,這是工作,但我只是保存在顯示p標籤的兩個值,我需要能夠實際兩個值的列表項的添加每次實例結束時將頁面底部保存到本地存儲,以便它們在啓動時顯示。這樣做最好的方法是什麼?我也希望能夠將這兩個記錄值的總量加起來並顯示出來。

回答

1

容易,並且不使用的數據結構:

var sumPay = 0; 
var sumHours = 0; 
for(var i = 0 ; i < localStorage.length; i++) { 
    var strKey = localStorage.key(i); 
    if(strKey.startsWith('myCachedPayPrefix_')) { 
     var cachedPay = localStorage.getItem(strKey); 
     sumPay = cachedPay; 
    } 
    if(strKey.startsWith('myCachedHoursPrefix_')) { 
     var cachedHours = localStorage.getItem(strKey); 
     sumHours += cachedHours; 
    } 
} 

更好:保持一個數組,並使用JSON.stringifyJSON.parse以移動陣列進出的localStorage的,但你可以操縱它像一個正確的數據結構體。

+0

感謝您的幫助!我結束了使用parsedpay = parseInt(localStorage [「paycount」] + 1;然後加載它與localStorage.paycount = parsedpay;將其添加並相應地分配名稱。 – user3473543 2014-10-08 19:09:05

相關問題