简体   繁体   English

这是实现cookie的正确方法吗?

[英]Is this the correct way to implement a cookie?

I am running the following code which loads a div and hies it according to cookie but does not show it back again once a cookie is set. 我正在运行以下代码,该代码加载div并根据cookie隐藏它,但是一旦设置cookie,就不会再次显示它。

I do not understand why this is not running. 我不明白为什么它没有运行。

<!DOCTYPE html>
<html>

<head></head>

    <body>
    <div style="width:250px;height:250px;background-color:#000;" id="PostShare">
    </div>
    </body>

    <script language="javascript" type="text/javascript" async>
    function createPages(name,value,days) {
       var date = new Date();
       date.setTime(date.getTime()+(days*24*60*60*1000));
       var expires = date.toGMTString();
       document.cookie = name+"="+value+"; expires="+expires+"; path=/";
    }

    function readPages(name) {
        var flag = 0;
        var dcmntPages = document.cookie.split(';');
        for(var i=0;i < dcmntPages.length;i++) {
            var ck = dcmntPages[i];
            while (ck.charAt(0)==' ') {
                ck = ck.substring(1,ck.length);
            }
            if(ck) {
                cparts = ck.split('=');
                if (cparts[0] == name) flag=1;
            }              
        }     
        if(flag) { 
            return true; 
        } else {
            return false; 
        }  
    }

    function checkPages(name) {
        if (readPages(name)) {
    document.getElementById('PostShare').style.display = "none";
    document.getElementById('PostShare').style.visibility = "hidden";
        }
        else {
    document.getElementById('PostShare').style.display = "block";
    document.getElementById('PostShare').style.visibility = "visible";
        createPages(name,"cookie 4 the day",1); 
        }
    }

    checkPages("MyPages");
    </script>
    </body>

</html>

I am trying the same on incognito and so but it does not work. 我正在隐身模式下尝试相同的操作,因此它不起作用。 Please help me understand how to make this code work or what should be the code for hiding a div for user on first load and showing it on rest of loads for the day. 请帮助我了解如何使此代码正常工作,或者应该是什么代码,以便在首次加载时为用户隐藏div并在当天的其余加载中显示该div。

Thanks 谢谢

Your implementation looks good. 您的实现看起来不错。 If your viewing the page in your browser from file, cookies won't set. 如果您在浏览器中通过文件查看页面,则不会设置cookie。 You need to host it on a server. 您需要将其托管在服务器上。 You can run simple server to host your html file : - python - apache - npm 您可以运行简单的服务器托管您的HTML文件: - 蟒蛇 - 阿帕奇 - NPM

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM