即使Cookie政策仍在有效期内,也会显示Div

时间:2018-10-07 15:07:37

标签: javascript jquery

下面的代码应该设置一个cookie,当单击一个按钮时它的有效期为60天,这可以,但是当我在另一个窗口中打开网站或刷新页面时,div仍然出现,我无法找出原因。

谁能阻止我写错了

(function () {
    "use strict";

    var cookieAlert = document.querySelector(".cookiealert");
    var acceptCookies = document.querySelector(".acceptcookies");

    cookieAlert.offsetHeight; // Force browser to trigger reflow (https://stackoverflow.com/a/39451131)

    if (!getCookie("acceptCookies")) {
       cookieAlert.classList.add("show");
    }

    acceptCookies.addEventListener("click", function () {
        setCookie("acceptCookies", true, 60);
        cookieAlert.classList.remove("show");
    });
})();

// Cookie functions stolen from w3schools
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=/";
}

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 "";
}

这是我正在使用的HTML

<div class="alert alert-dismissible text-center cookiealert show" role="alert">
    <div class="cookiealert-container">
        @privacyText <a href="@privacyLink">Learn more</a>

        <button id="btnCookiePolicy" type="button" class="btn btn-primary btn-sm acceptcookies" aria-label="Close">
            I agree
        </button>
    </div>
</div>

1 个答案:

答案 0 :(得分:1)

这是错误的...

RecyclerView

您需要从类列表中删除类<div class="alert alert-dismissible text-center cookiealert show" role="alert"> ,因为您希望默认情况下隐藏该对话框,然后在没有cookie的情况下添加show类。

只需将该行更改为此...

show

那应该可以解决您的问题。