手机
当前位置:查字典教程网 >编程开发 >Javascript教程 >使用jquery读取html5 localstorage的值的方法
使用jquery读取html5 localstorage的值的方法
摘要:在HTML5中,localstorage是个不错的东西,在支持localstorage的浏览器中,能持久化用户表单的输入,即使关掉浏览器,下...

在HTML 5中,localstorage是个不错的东西,在支持localstorage的浏览器中, 能持久化用户表单的输入,即使关掉浏览器,下次重新打开浏览器访问,也能读出其值, 下面给出的例子是使用jquery 在每次表单加载的时候,读localstorage的值,而在表单每次提交时则清楚其值的例子

首先是一个表单:

复制代码 代码如下:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>HTML5 Local Storage Example</title>

<>

<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/css/bootstrap-combined.min.css" rel="stylesheet">

</head>

<body>

<div>

<h1>HTML5 Local Storage Example</h1>

<form method="post">

<fieldset>

<legend>Enquiry Form</legend>

<div>

<label for="type">Type of enquiry</label>

<div>

<select name="type" id="type">

<option value="">Please select</option>

<option value="general">General</option>

<option value="sales">Sales</option>

<option value="support">Support</option>

</select>

</div>

</div>

<div>

<label for="name">Name</label>

<div>

<input type="text" name="name" id="name" value="" maxlength="50">

</div>

</div>

<div>

<label for="email">Email Address</label>

<div>

<input type="text" name="email" id="email" value="" maxlength="150">

</div>

</div>

<div>

<label for="message">Message</label>

<div>

<textarea name="message" id="message"></textarea>

</div>

</div>

<div>

<div>

<label>

<input name="subscribe" id="subscribe" type="checkbox">

Subscribe to our newsletter

</label>

</div>

</div>

</fieldset>

<div>

<input type="submit" name="submit" id="submit" value="Send">

</div>

</form>

</div>

然后是js部分代码:

复制代码 代码如下:

<script src="http://www.jb51.net/code.jquery.com/jquery-latest.js"></script>

<script>

$(document).ready(function () {

/*

* 判断是否支持localstorage

*/

if (localStorage) {

/*

* 读出localstorage中的值

*/

if (localStorage.type) {

$("#type").find("option[value=" + localStorage.type + "]").attr("selected", true);

}

if (localStorage.name) {

$("#name").val(localStorage.name);

}

if (localStorage.email) {

$("#email").val(localStorage.email);

}

if (localStorage.message) {

$("#message").val(localStorage.message);

}

if (localStorage.subscribe === "checked") {

$("#subscribe").attr("checked", "checked");

}

/*

* 当表单中的值改变时,localstorage的值也改变

*/

$("input[type=text],select,textarea").change(function(){

$this = $(this);

localStorage[$this.attr("name")] = $this.val();

});

$("input[type=checkbox]").change(function(){

$this = $(this);

localStorage[$this.attr("name")] = $this.attr("checked");

});

$("form")

/*

* 如果表单提交,则调用clear方法

*/

.submit(function(){

localStorage.clear();

})

.change(function(){

console.log(localStorage);

});

}

});

【使用jquery读取html5 localstorage的值的方法】相关文章:

jQuery实现表格行上移下移和置顶的方法

js+html5实现canvas绘制简单矩形的方法

javascript获取select值的方法分析

jquery简单实现外部链接用新窗口打开的方法

jQuery实现dialog设置focus焦点的方法

js+html5绘制图片到canvas的方法

jquery预加载图片的方法

jQuery取消ajax请求的方法

jQuery获取上传文件的名称的正则表达式

Jquery动态添加输入框的方法

精品推荐
分类导航