如何将removeItem()与localstorage一起使用? [英] How do I use removeItem() with localstorage?

查看:387
本文介绍了如何将removeItem()与localstorage一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





SetItem()和getItem()使用以下代码,但不能使用removeItem()。在删除对象之前是否需要格式化对象?代码如下。干杯。



<!DOCTYPE HTML> 
< html>
< body>

< script>

function storeusername()
{
var person = {};
person.age = 25;
person.firstname ='Joe';
person.lastname ='史密斯';
localStorage.setItem('persondetails',JSON.stringify(person));
}

function getusername()
{
var person = JSON.parse(localStorage.getItem('persondetails'));
document.getElementById('username')。innerHTML = person.age +''+ person.firstname +''+ person.lastname;
}

function clearusername()
{
localstorage.removeItem('personaldetails');
}

< / script>
< br />
名称:< p id =username>< / p>
< input type = button value =Storeonclick =storeusername()/>
< input type = button value =Retrieveonclick =getusername()/>
< input type = button value =Clearonclick =clearusername()/>
< / body>
< / html>

解决方案

removeItem 是正确的,但你必须指定正确的密钥。要添加你使用 persondetails 的东西,并删除你使用 personaldetails ,这样就无法使用了。



  //   localStorage with capital S(非常重要,localstorage未定义)。 
// 关键是persondetails,非个人详细信息。
localStorage.removeItem(' persondetails');


Hi,

SetItem() and getItem() work with the following code, but not removeItem(). Do I need to format the object before removing it? Code below. Cheers.

<!DOCTYPE HTML>
<html>
<body>

<script>

function storeusername()
{
	var person = {};
	person.age = 25;
	person.firstname = 'Joe';
	person.lastname = 'Smith';
	localStorage.setItem('persondetails', JSON.stringify(person));
}

function getusername()
{
	var person = JSON.parse(localStorage.getItem('persondetails'));
	document.getElementById('username').innerHTML = person.age + ' ' + person.firstname + ' ' + person.lastname;
}

function clearusername()
{
	localstorage.removeItem('personaldetails');
}

</script>
<br/>
Name: <p id="username"></p>
<input type=button value="Store" onclick="storeusername()" />
<input type=button value="Retrieve" onclick="getusername()" />
<input type=button value="Clear" onclick="clearusername()" />
</body>
</html>

解决方案

removeItem is correct, but you have to specify the right key. To add stuff you use persondetails and to remove you use personaldetails, so that's not going to work.

// localStorage is with capital S (very important, localstorage is undefined).
// The key is persondetails, and not personaldetails.
localStorage.removeItem('persondetails');


这篇关于如何将removeItem()与localstorage一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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