基于Cookie存在更改HTML按钮

时间:2014-11-14 02:01:37

标签: javascript html css cookies conditional-statements

我想编辑一个html按钮,告诉用户他们是否已阅读按钮所在的页面。按钮位于页面底部,开始呈红色。用户按下按钮后,会生成一个cookie,并且changeButton()函数会检查cookie是否已创建,然后将按钮更改为绿色。即使用户关闭并重新打开浏览器,该按钮仍应保持绿色,直到cookie被删除。

在我按下按钮之前,我的浏览器只是在页面加载时将按钮显示为绿色。任何帮助将不胜感激。

<head>
<script type="text/javascript">

    function changeButton()
    {

        var name = 'user_read_the_page' + '=';
        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) != -1)
            {
                var output = c.substring(name.length,c.length);
            }
        }       

        document.getElementById("test").innerText = output;

        if(output == 1)
        {
            cookie_exists = 1;
        }
        else
        {
            cookie_exists = 0;
        }           

        if(cookie_exists == 1)
        {
            document.getElementById("read_button").style.backgroundColor = "green";
            document.getElementById("read_button").style.color = "white";
            document.getElementById("read_button").style.fontWeight = "bold";
            document.getElementById("read_button").innerText = "\u2714 You Have Read This Page";
        }
        else
        {
            document.getElementById("read_button").style.backgroundColor = "red";
            document.getElementById("read_button").style.color = "white";
            document.getElementById("read_button").style.fontWeight = "bold";
            document.getElementById("read_button").innerText = "\u2718 Please Read This Page";              
        }

        return "";
    }
</script>
</head>

...

<button id="read_button" onclick="createCookie('user_read_the_page', 30)"></button>

    <script language="javascript">

        function createCookie(name, days)
        {
            var expire = new Date ();
            expire.setTime (expire.getTime() + (24 * 60 * 60 * 1000) * days); 
            document.cookie = name + "=1; expires=" + expire.toGMTString();
            changeButton();
        }

    </script>

0 个答案:

没有答案