js设置cookie(简单保存cookie)

<h2>Coookie</h2>
<input id="Button1" type="button" onclick="savaCookie()" value="保存cookie" />
<input id="Button2" type="button" onclick="getCookie('userId')" value="读取cookie" />
<script>
    function savaCookie() {
        var date = new Date();
        var expiresDays = 24;
        date.setTime(date.getTime() + expiresDays * 24 * 3600 * 1000);
        document.cookie = "userId=自己设置的Cookie内容" + ";expires" + date.toGMTString();
    }
    function getCookie(key) {
        var getCookie = document.cookie.replace(/[]/g, "");
        var arrCookie = getCookie.split(";")
        var tips;
        for (var i = 0; i < arrCookie.length; i++) {
            var arr = arrCookie[i].split("=");
            if (key == arr[0]) {
                tips = arr[1];
                break;
            }
        }
        alert("获取Cookie内容:" + tips);
    }
</script>

 

posted @ 2020-06-17 17:03  般若不是ban,nuo  阅读(351)  评论(0编辑  收藏  举报