为什么我的本地存储在刷新后不保留变量的值?

Why is my localstorage not keeping the variable's value after refresh?

所以我有一些代码,我想在进入另一个页面后保留某个变量的值,当我返回原始页面并按下某个按钮时,它会增加它的值并保持增加的值.问题是代码似乎没有按预期工作。变量的默认值为 0,按下按钮时它增加 2 并使用本地存储保存,然后我被发送到我的另一个页面,然后当我返回原始页面并再次按下相同的按钮时变量是再次 2. 为什么会这样? 这是我的代码:

$(document).ready(function()
{
    var isShoes = false
    var isShirt = false
    var oneMoreShoe = false
    var buttonClicked = 0;

    $('#purchaseShoes').on('click', function()
    {
        buttonClicked+=2;
        var Shoes = localStorage.setItem('img_shoes', '/static/Images/Sneakers.png')
        var clicksCounter = localStorage.setItem('buttonClicked', JSON.stringify(buttonClicked))
        var retainClicksCount = localStorage.getItem('buttonClicked')
        var actualClickCount = JSON.parse(retainClicksCount)
        isShoes = localStorage.setItem('isShoes', true)
        alert(retainClicksCount)
        if(retainClicksCount>= 4){
            oneMoreShoe = localStorage.setItem('oneMoreShoe', true)
         }
    })
    
})
$(document).ready(function()
{
    var isShoes = false
    var isShirt = false
    var oneMoreShoe = false
    var buttonClicked = 0;
    
    if (localStorage.getItem('buttonClicked')) // check if button click exists in storage and assign it to your variable
    {
        buttonClicked = localStorage.getItem('buttonClicked');
    }
    $('#purchaseShoes').on('click', function()
    {
        buttonClicked+=2;
        var Shoes = localStorage.setItem('img_shoes', '/static/Images/Sneakers.png')
        var clicksCounter = localStorage.setItem('buttonClicked', JSON.stringify(buttonClicked))
        var retainClicksCount = localStorage.getItem('buttonClicked')
        var actualClickCount = JSON.parse(retainClicksCount)
        isShoes = localStorage.setItem('isShoes', true)
        alert(retainClicksCount)
        if(retainClicksCount>= 4){
            oneMoreShoe = localStorage.setItem('oneMoreShoe', true)
         }
    })
})

每次您更新页面时,您的 buttonClicked 变量变为 = 0。您需要检查局部变量是否存在,如果存在,您可以从 localstorage 获取脚本变量的值,然后添加 2 并使用它。