血泪提示:innerHTML和value都是用于向html中导入值, 但是
innerHTML 是用于div, p 等纯HTML的标签,value 用于可输入的标签如 input等。
项目过程中用户提到要我们提供一种可以记录用户输入的模板,起初准备用cookie实现,但是模板太过于复杂,所以就放弃了,改用数据库。。。所以的写了一个晚上的cookie就白写了。。。不过为了让以后的工作方便调用,我就把它修改了一下,放了上来。
<!DOCTYPE html>
<html>
<html>
<head>
<meta charset="utf-8">
<title>cookie</title>
</head>
<link rel="stylesheet" href="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="http://cdn.static.runoob.com/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<head>
<script>
//记录已经输入的数据到cookie
function record(){
if (document.getElementById("checkbox").checked)
{
var first_item = document.getElementById("name").value;
document.cookie = "name" +"=" + first_item;
var second_item = document.getElementById("sex").value;
document.cookie = first_item + "=" + second_item;
var third_item = document.getElementById("appearance").value;
document.cookie = second_item + "=" + third_item;
}
}
//从cookie中取出对应的数据
function fill_in_auto(first_row_item){
var cookies = document.cookie.split(';');
var items_left = first_row_item + "=";
for (var i = 0; i < cookies.length; i++)
{
if (cookies[i].indexOf(items_left) == 1)
{
document.getElementById("sex").value = cookies[i].substring(items_left.length + 1);
var items_left = cookies[i].substring(items_left.length + 1) + "=";
break;
}
}
for (var i = 0; i < cookies.length; i++)
{
if (cookies[i].indexOf(items_left) == 1)
{
document.getElementById("appearance").value = cookies[i].substring(items_left.length + 1);
break;
}
}
}
// 监听函数
function checkCookie(){
var input = document.getElementById("name").value;
// document.getElementById("test").innerHTML = document.cookie;
fill_in_auto(input);
}
</script>
</head>
<body>
<form class="form-horizontal" role="form">
<div class="form-group">
<label for="firstname" class="col-sm-2 control-label">名字</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="name"
placeholder="请输入名字" onchange = "checkCookie()">
</div>
</div>
<div class="form-group">
<label for="lastname" class="col-sm-2 control-label">Sex</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="sex"
placeholder="男女?">
</div>
</div>
<div class="form-group">
<label for="lastname" class="col-sm-2 control-label">外貌</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="appearance"
placeholder="帅否?">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<div class="checkbox">
<label>
<input type="checkbox" id = "checkbox"> 请记住我
</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default" onclick = "record()">登录</button>
</div>
</div>
</form>
</body>
</html>
效果图
一旦输入过一次,并且选择了记录,那么整个info在登录过程中就会被记录下来。
下一次只要输入名字,就会自动填写剩下的内容。(代码经过了检测,可用)
技术
- cookie的调用
- 监听: onclick, onchange
- 对box的状态检测。
网友评论