我目前正在嘗試允許用戶輸入一個值,然后將其添加到總數中,然后在本地存盤。我想允許用戶加載他們以前的總數,然后通過相同的輸入添加更多。
實際發生的是,當用戶加載到頁面上時,先前存盤的值作為字串加載。我不確定如何將其更改為整數,以便用戶可以向其中添加另一個整數。這個更新后的總數需要顯示到一個 html 元素。
//Load current total or set to 0
var calories = localStorage.getItem("calorieCount") || 0;
//Display current total
$('[id=calorieCount]').html(calories);
//On add
$('#calorie-add').click(function () {
//Take current total and add user input
calories = parseInt(document.getElementById('adjust-input').value);
//Update current total to local storage
localStorage.setItem('calorieCount', calories);
//Display new total
$('[id=calorieCount]').html(calories);
});
我知道本地存盤的任何內容都存盤為字串,但我看到有人提到將其決議為整數并允許用戶運算元字。但我不確定他們是如何做到這一點的。
非常感謝任何幫助:D
uj5u.com熱心網友回復:
您需要在第一次加載時將本地存盤值決議為 int,如下所示:
var calories = parseInt(localStorage.getItem("calorieCount")) || 0;
uj5u.com熱心網友回復:
在這種情況下,您可以使用 Number() 函式將 localStorage.getItem("calorieCount") 字串決議為數字,根據用戶輸入更改值,然后將新值保存到 localStorage。嘗試使用此代碼:
var calories = Number(localStorage.getItem("calorieCount")) || 0;
$('[id=calorieCount]').html(calories);
$('#calorie-add').click(function () {
calories = Number(document.getElementById('adjust-input').value);
//Update current total to local storage
localStorage.setItem('calorieCount', calories);
//Display new total
$('[id=calorieCount]').html(calories);
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/490145.html
標籤:javascript html
上一篇:Heroku無法自動檢測到用于此應用程式的buildpack。嘗試將檔案部署/推送到heroku時出錯-有什么修復嗎?
