如何用jQuery隐藏元素取决于cookie值?

时间:2019-02-08 23:07:58

标签: javascript jquery

首先,我需要将cookie cookiesshow的值设置为true,单击按钮后,我需要询问cookiesshow是否为true以及是否为hide元素,然后将cookiesshow的值设置为false但不起作用。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> 
</script>
<script>
$(document).ready(function(){
    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 "";
    }

    if (getCookie("cookiesshow") != false)
    {
        document.cookie = "cookiesshow=true";
    }
    else
    {
        $("#cookiebar").hide();
    }

    $("#cookiebutton").click(function(){
        var cookie = getCookie("cookiesshow");
        console.log(cookie);
        if (cookie == "true") {
            $("#cookiebar").hide(1000);
            document.cookie = "cookiesshow=false";
        }
    })
});
</script>

<div class="cookiebar" id="cookiebar"><span>This web using cookies. If you disagree with using cookies, please leave this page. </span><button class="cookiebutton" id="cookiebutton">Accept cookies</button></div>

2 个答案:

答案 0 :(得分:1)

设置cookie时,所有cookie都将保存为字符串。

$(document).ready(function(){
    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 setCookie(cname, cvalue, exdays) {
        var d = new Date();
        d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
        var expires = "expires="+d.toUTCString();
        document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
    }

    if (getCookie("cookiesshow") !== "false")
    {
        setCookie("cookiesshow",true,3650);
        //document.cookie = "cookiesshow=true";
    }

    $("#cookiebutton").click(function(){
        var cookie = getCookie("cookiesshow");
        console.log(cookie);
        if (cookie === "true") {
            $("#cookiebar").hide(1000);
            setCookie("cookiesshow",false,3650);
            //document.cookie = "cookiesshow=false";
        }
    })
});

答案 1 :(得分:0)

您不需要具有默认设置cookiesshow=true。单击按钮后,设置cookie cookiesshown=true并实现显示元素可见性的逻辑,该元素可见性取决于cookie值。更好的用户localStoragelocalStorage.getItem('cookiesshown'); / localStorage.setItem('cookiesshown', 'true');)为此目的,但始终可以访问存储(例如https://stackoverflow.com/a/16427747/8521615)。在加载元素之前,首先检查localStorage项是否存在,如果不存在则显示为-show。如果需要单击,则应将其隐藏。