将变量的值存储在本地存储中

阿卜杜勒·拉赫曼·法拉格

我有一个简单的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));


    })
})

感谢您的支持。

萨加尔·阿格罗瓦尔(Sagar Agrawal)

您可以使用此代码。在这里,如果存在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));
    });
});

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章