zoukankan      html  css  js  c++  java
  • JavaScript中Cookie的用法

    Javascript中Cookie主要存储于客户端的计算机中,用于存放已访问的站点信息,Cookie最大约为4k.以下实例主要用于页面在刷新时保存数据,具体的用法如下所示:

    <html>
    <head><title></title>
    </head>
    <body>
    <script type="text/javascript">
        window.onload = function ()
        {
            PersentValue();
        }
    
        function AddValueToCookie()
        {
            setCookie("ID", 100);
            setCookie("Name", 'Tom');
            PersentValue();
        }
    
        function ClearValueOfCookie()
        {
            SetCookieToExpire("ID");
            SetCookieToExpire("Name");
            PersentValue();
        }
    
        function PersentValue()
        {
            var id = getCookie("ID");
            var name = getCookie("Name");
            if (id == null) {
                alert('Waiting for set value to ID');
            }
            else {
                alert(id);
            }
    
            if (name == null) {
                alert('Waiting for set value to Name');
            }
            else {
                alert(name);
            }
        }
    
        function setCookie(name, value) {
            var Days = 30;
            var exp = new Date();
            exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
            document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString();
        }
    
        function getCookie(name) {
            var arg = name + "=";
            var alen = arg.length;
            var clen = document.cookie.length;
            var i = 0;
            while (i < clen) {
                var j = i + alen;
                if (document.cookie.substring(i, j) == arg) {
                    return getCookieVal(j);
                }
                i = document.cookie.indexOf(" ", i) + 1;
                if (i == 0) break;
            }
            return null;
        }
    
        function getCookieVal(offset) {
            var endstr = document.cookie.indexOf(";", offset);
            if (endstr == -1) {
                endstr = document.cookie.length;
            }
            return unescape(document.cookie.substring(offset, endstr));
        }
    
        function SetCookieToExpire(name) {
            var exp = new Date();
            exp.setTime(exp.getTime() - 1);
            var cval = getCookie(name);
            if (cval != null) document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
        }
    </script>
    <input type="button" value="AddValue" onclick="AddValueToCookie();" />
    <input type="button" value="ClearValue" onclick="ClearValueOfCookie();" />
    </body>
    </html>
    View Code

    参考链接

  • 相关阅读:
    js 实现页面局部(或图片)放大功能(vue)
    momentjs 使用总结
    VUX的使用方法(以弹出框为例)
    vue alert插件(标题为图片)(自写)
    vue 五星评价插件
    ES6 学习笔记(基础)
    SVG
    纯 CSS 实现实心三角形和空心三角形
    selectedIndex和onchange事件
    DOM文档获取和简介
  • 原文地址:https://www.cnblogs.com/sccd/p/5535779.html
Copyright © 2011-2022 走看看