如何从用户输入获取cookie,并将其显示在html元素上

时间:2015-11-13 21:52:21

标签: javascript html cookies

我正在建立一个使用cookie来获取用户名的网站。当我尝试使用inner.html显示它时,它甚至不会提示用户。这是我的代码。该区域具体是函数checkCookie()

    <!DOCTYPE html>
    <html>
    <head>
    <script>

    function setCookie(cname,cvalue,exdays) {
        var d = new Date();
        d.setTime(d.getTime() + (exdays*24*60*60*1000));
        var expires = "expires=" + d.toGMTString();
        document.cookie = cname+"="+cvalue+"; "+expires;
    }

    function getCookie(cname) {
        var name = cname + "=";
        var ca = document.cookie.split(';');
        for(var i=0; i<ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0)==' ') c = c.substring(1);
            if (c.indexOf(name) == 0) {
                return c.substring(name.length, c.length);
            }
        }
        return "";
    }

    function checkCookie() {
        var user=getCookie("username");
         if (user != null) {
            document.getElementById("person").innerHTML =
            "Hello " + user + "!";
        } else {
           user = prompt("Please enter your name:","");
           if (user != "" && user != null) {
               setCookie("username", user, 30);
           }
        }
    }

    </script>
    </head>
    <body onload="checkCookie()">
    <p id="person">anonymous user</p>
    </body>
    </html>

1 个答案:

答案 0 :(得分:1)

更改

return "";

为:

return null;

checkCookie期望getCookie在找不到Cookie时返回null。空字符串与null不同。

DEMO