在按钮上显示/隐藏div单击并保存Cookies

时间:2018-09-29 18:42:42

标签: javascript html cookies onclick show-hide

我使用此javascript代码编写Cookie和显示/隐藏;

$(document).ready(function () {

        if (Boolean(readCookie('hide'))) {
            $('.pop-up').hide();
            $('.pop-up').fadeOut(1000);
        }
        $('.close-button').click(function (e) {

            $('.pop-up').fadeOut(700);
            $('#overlay').removeClass('blur-in');
            $('#overlay').addClass('blur-out');
            e.stopPropagation();

            createCookie('hide', true, 1)
            return false;
        });

        function createCookie(name, value, days) {
            if (days == 1) {
                var date = new Date();
                date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                var expires = "; expires=" + date.toGMTString();
            }
            else var expires2 = "";
            document.cookie = name + "=" + value + "; expires=" + expires + "; path=/";

          //  $.cookie(name, value, { expires: days });
        }

        function readCookie(name) {
            var nameEQ = name + "=";
            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, c.length);
                if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
            }
            return null;
        }

        function eraseCookie(name) {
            createCookie(name, "", -1);
        }

    });

我在同一页面上需要10个按钮,但我不能。因为如果我单击关闭按钮 (X),所有按钮都将隐藏。我需要一张一张的皮。

我尝试更改名称和值,但未成功。

这是HTML;

<div id="overlay" class="cover blur-in">
    <div class="content"></div>
</div>
<div class="row pop-up">
    <div class="box small-6 large-centered">
        <a href="#" class="close-button">✖</a>
        <h3 class="popup">Welcome</h3>
        <p>info </p>
        <p>info</p>
        <a href="#" class="button">press for facebook</a>
    </div>
</div>

This is jsfiddle for this code

1 个答案:

答案 0 :(得分:0)

您的jsfiddle似乎不起作用(空白),但是通常的想法是使用close_button类遍历所有元素,并为每个元素添加一个侦听器,如下所示:

$('.close-button').each(function(i, obj) {
     $(this).click(function (e) {
         $('.pop-up').eq(i).fadeOut(700);
         $('#overlay').removeClass('blur-in');
         $('#overlay').addClass('blur-out');
         e.stopPropagation();
         return false;
     })
});