js本地化操作,设置cookie、获取cookie,删除cookie的例子:
参考网站:w3c js操作cookie
代码:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <button id="btn1" onclick="setCookies()">设置cookies</button> <button id="btn2" onclick="getCookies()">读取cookies</button> <button id="btn3" onclick="clearCookies()">清除cookies</button> </body> <script type="text/javascript"> function setCookies(){ setCookie('name', 'zhangsan'); setCookie('password', '123456', 2); setCookie('age', '12'); } function getCookies(){ var name = getCookie('name'); var password = getCookie('password'); var age = getCookie('age'); console.log("name:"+name+" password:"+password+" age:"+age); } function clearCookies(){ deleteCookie('name'); deleteCookie('age'); deleteCookie('password'); } /** * 设置cookie 键值对形式 * name 存储的key * value 对应的值 * expiredays 过期时间 天数 如果为null的话不设置过期时间 * 不设置这个值的话,cookie默认在关闭浏览器时失效 */ function setCookie(name, value, expiredays){ var exdate=new Date(); if(expiredays==null || typeof(expiredays)=='undefined'){ document.cookie = name + "="+escape(value); }else{ exdate.setDate(exdate.getDate()+expiredays); document.cookie = name + "="+escape(value)+";expires="+exdate.toGMTString(); } } /** * 读取cookie */ function getCookie(name){ if(document.cookie.length>0){ var start = document.cookie.indexOf(name + "="); if(start != -1){ start = start + name.length + 1; end = document.cookie.indexOf(";",start); if(end == -1){ end = document.cookie.length; } return unescape(document.cookie.substring(start, end)); } } return null; } /** * 删除cookie */ function deleteCookie(name){ var exp = new Date(); exp.setTime(exp.getTime() - 1000); //当前时间减去一秒,相当于立即过期(可以增减) var val = getCookie(name); if(val!=null){ document.cookie = name + "="+val+";expires="+exp.toGMTString(); } } </script> </html>
password设置了过期时间,看设置过期时间与不设置过期时间的区别: