<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <form action="http://www.baidu.com" id="frm"> 用户名<input type="text" name="" id=""> 密码<input type="password" name="" id=""> <input type="submit" value="登陆"> <a href="javascript:;" id="clear">清除记录</a> </form> <script> function setCookie (name, value, iDay){ var oDate = new Date(); oDate.setDate(oDate.getDate()+iDay); document.cookie = name+"="+value+";expires="+oDate; } function getCookie (name){ var cookieArr = document.cookie.split("; "); for (var i = 0; i < cookieArr.length; i++) { var oneCookie = cookieArr[i].split("="); if (oneCookie[0] === name) { return oneCookie[1]; } } return ''; } function removeCookie (name) { setCookie(name, '1', -1); } function addListener (target, type, handler) { if (target.attachEventListener) { target.attachEventListener(type, handler, false); } else if (target.attachEvent) { target.attachEvent("on"+type, handler); } else { target["on"+type] = handler; } } window.onload = function (){ var oForm = document.getElementById("frm"); var oUser = oForm.getElementsByTagName("input")[0]; var oClear = oForm.getElementsByTagName("a")[0]; oForm.onsubmit = function (){ var username = oUser.value; setCookie("username", username, 30); } oUser.value = getCookie('username'); addListener(oClear, "click", function(){ removeCookie("username"); oUser.value = ''; }); } </script> </body> </html>
只有在firefox下,可以直接用浏览器打开文件测试,所以建议上传至服务器端~