尝试使用键名从localstorage中删除项目 [英] trying to remove item from localstorage using the key name

查看:114
本文介绍了尝试使用键名从localstorage中删除项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从localstorage中删除项目,或者在按钮单击时清除它。我编写了代码但是在单击按钮时,它不会清除本地存储数据。这是带有localstorage数据的变量

I am trying to remove item from localstorage or rather clear it on button click. I have written the code but on clicking on the button, it does not clear the localstorage data. this is the variable with the localstorage data

    window.onbeforeunload = function() {
    localStorage.setItem("first_name", $('#inputName').val());
};

EDITTED

window.onload = function() {
    var name = localStorage.getItem("first_name");
    if (name !== null) {
        $('#inputName').val(name);
        alert(name);
    }
};

这是清算存储的功能

function clearStorage(){
alert('localstorage cleared!');
localStorage.removeItem('first_name');

}

按钮的片段单击代码块以使用键名清除localstorage数据

the snippet of the button click code block to clear localstorage data using the key-name

<input type="text" id="inputName" placeholder="Name" required>
<button onclick="clearStorage()">clear</button>

点击按钮试图从本地存储中清除数据并刷新页面,本地存储数据仍在输入值中。
如何清除本地存储内容是我的挑战

on clicking the button in attempt to wipe out the data from the localstorage and refreshing the page, the localstorage data is still in the input value. how to clear localstorage content is my challenge

推荐答案

您已成功删除该项目 —然后当你刷新时,当你离开页面时,你再次设置,因为你还有:

You're successfully removing the item — and then when you refresh, you're setting it again as you leave the page, because you still have:

window.onbeforeunload = function() {
    localStorage.setItem("first_name", $('#inputName').val());
};

您必须决定何时设置项目。即使你之前已经清除它,上面也会一直这样做。

You'll have to decide when you want to set the item. The above will always do it, even if you've cleared it previously.

也许你最好只在时设置项目输入更改, onbeforeunload 中的。也就是说,摆脱上述,而是:

Perhaps you'd be better off only setting the item when the input changes, and not in onbeforeunload. That is, getting rid of the above, and instead:

$("#inputName").on("input", function() {
    localStorage.setItem("first_name", $(this).val());
});

这样,如果您清除该项目(从本地存储中删除它),它将无法获得除非您再次编辑该字段,否则会添加回来。

That way, if you clear the item (remove it from local storage), it won't get added back unless you edit the field again.

这篇关于尝试使用键名从localstorage中删除项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆