分享一段代码实例,它简单演示了localStorage的使用。
代码实例如下:
0102030405060708091011121314151617181920212223242526272829303132333435363738<!doctype html>
<
html
>
<
head
>
<
meta
charset
=
"utf-8"
>
<
title
>记住密码</
title
>
</
head
>
<
body
>
用户名<
input
type
=
"text"
id
=
"ursename"
> <
br
>
密码 <
input
type
=
"text"
id
=
"password"
> <
br
>
<
input
id
=
"chk"
type
=
"checkbox"
>
<
lable
for
=
"chk"
>自动登录</
lable
>
<
script
>
//localStorage.getItem('')获取要存储的值
$('#chk').click(function() {
if (this.checked) {
//将值存储在本地
localStorage.setItem('names', $("#ursename").val());
localStorage.setItem(('pass'), $('#password').val());
// alert(localStorage.getItem('names'));
// alert(localStorage.getItem('pass'))
} else {
//在本地删除存储
localStorage.removeItem('names');
localStorage.removeItem('pass');
// console.log(localStorage.getItem('names'))
}
})
//判断是否有存储值如果有的话取出存储的值
if (localStorage.getItem('names') && localStorage.getItem('pass')) {
$('#ursename').val(localStorage.getItem('names'));
$('#password').val(localStorage.getItem('pass'));
$('#chk').prop("checked", true);
}
</
script
>
</
body
>
</
html
>