我有一个简单的Web应用程序,带有变量(var VacationBalance = 21)。我希望每次用户单击按钮时将这个值减1(ID为decrement)。另外,我希望将此保存在本地存储中。但是,它根本无法正常工作。
这是HTML:
<h1>Current Vacations: <span id="VacationsBalance"></span></h1>
<p><button id="show-form">Submit a new Vacation</button></p>
<form id="VacationForm" style="display:none;">
<div class="from-group">
<label for="exampleFormControlInput1">Select Vacation Type</label>
<select class="form-control">
<option>Annual</option>
<option>Casual</option>
</select>
</div>
<button type="submit" class="btn btn-primary" id="decrement">Confrim</button>
</form>
这是Javascript:
var VacationBalance=21;
var data = JSON.parse(localStorage.getItem('user'));
$(document).ready(function(){
if (localStorage) {
$("#VacationsBalance").text(data);}
else {
$("#VacationsBalance").text(VacationBalance);
}
})
window.onload = function() {
var showForm=document.getElementById('show-form');
showForm.addEventListener('click',function(){
document.getElementById('VacationForm').style.display="";
});
}
$(document).ready(function(){
$("#decrement").click(function(){
VacationBalance--;
$("#VacationsBalance").text(VacationBalance);
localStorage.setItem('user', JSON.stringify(VacationBalance));
})
})
感谢您的支持。
答案 0 :(得分:0)
当您从localStorage读取数据时,需要更新VactionBalance值以反映新值;这是一个清理的版本:
// get your initial setting from default or localStorage
var VacationBalance=21;
var data = JSON.parse(localStorage.getItem('user'));
// if localStorage had the value, update VacationBalance
if(data) {
// get the integer value in case it was stored as a string
VacationBalance = parseInt(data, 10);
}
// set up jQuery on document.ready
$(document).ready(function(){
// VacactionBalance will now always be accurate to default or loaded localStorage value
$("#VacationsBalance").text(VacationBalance);
// refactored to jQuery like the other stuff
$('#show-form').click(function() {
$('#VacationForm').css('display','');
});
// added all three into one document.ready call
$("#decrement").click(function(){
VacationBalance--;
$("#VacationsBalance").text(VacationBalance);
localStorage.setItem('user', JSON.stringify(VacationBalance));
});
});
您唯一真正缺少的是在页面加载时从localStorage更新VacationBalance值。
答案 1 :(得分:0)
您可以使用此代码。在这里,如果存在localStorage并且还存在数据,我们将使用来自localStorage的值加载VacationBalance变量。单击按钮将更新localStorage。
enter code here
var VacationBalance = 21;
var data = JSON.parse(localStorage.getItem('user'));
$(document).ready(function(){
if (localStorage) {
if(data) {
VacationBalance = parseInt(data, 10);
}
$("#VacationsBalance").text(VacationBalance);
}
else {
$("#VacationsBalance").text(VacationBalance);
}
});
window.onload = function() {
var showForm=document.getElementById('show-form');
showForm.addEventListener('click',function(){
document.getElementById('VacationForm').style.display="";
});
}
$(document).ready(function(){
$("#decrement").click(function(){
VacationBalance--;
$("#VacationsBalance").text(VacationBalance);
localStorage.setItem('user', JSON.stringify(VacationBalance));
});
});