zoukankan      html  css  js  c++  java
  • [javascript]在浏览器端应用cookie记住用户名

    <!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下,可以直接用浏览器打开文件测试,所以建议上传至服务器端~

  • 相关阅读:
    各个download文件说明
    网页中播放FLV文件的代码
    关于外部样式表中backgroundimage:url()的设置
    C# VS 2010创建、安装、调试 windows服务(windows service)
    HttpUtility.UrlEncode,Server.UrlEncode 的区别
    关于Coolite(EXT)问题之一
    Trace 日志文件
    document对象
    让IE6/IE7/IE8浏览器支持CSS3属性特效
    自定义URL Protocol Handler 呼出应用程序
  • 原文地址:https://www.cnblogs.com/zhongshanblog/p/4655624.html
Copyright © 2011-2022 走看看