如何使用按钮清除localStorage?

时间:2015-06-13 07:19:44

标签: javascript local-storage

我想创建一个按钮,为用户清除localstorage。使用localStorage.clear();但它不起作用。

如果您查看演示,则无效。

Demo

JS code:

var money = 0;

//localStorage function

if(localStorage.money) money = localStorage.getItem('money');
document.getElementById("money").innerHTML = money;

//Clicking function

function moneyClick(number){
    money = parseInt(money) + 10;
    document.getElementById ("money").innerHTML = money;
    localStorage.setItem('money', money);
}

//clear data function

function clearClick(number){
    localStorage.clear();
}

1 个答案:

答案 0 :(得分:2)

您的代码确实清除localStorage,但您需要刷新页面才能看到它。在您的代码中,您可以通过将money设置为0并在清除localStorage时更新DOM来更清晰地显示:

function clearClick(number){
    localStorage.clear();
    money = 0;
    document.getElementById ("money").innerHTML = money;
}