读多个cookie

时间:2015-02-06 10:00:33

标签: jquery html cookies

我想知道如何检测多个Cookie。我有两个带有class- .attack_enabled和.restore_enabled的按钮,它们分别创建了一个名为attackcompletecookie和restorecompletecookie的cookie。

如何检测两个Cookie并将类添加到.territory_middle_complete

这是我的代码:

$(".attack_enabled").click(function(){

   createCookie('attackcompletecookie','attack_cookie');

});

$(".restore_enabled").click(function(){

   createCookie('attackcompletecookie','restore_cookie');
   var atkcomplete = readCookie('attackcompletecookie');

});

if(atkcomplete){
   console.log(atkcomplete);
   $(".territory_middle_complete").addClass("displayblockzindex2");
}

1 个答案:

答案 0 :(得分:0)

尝试使用id而不是类来引用jQuery,留下CSS的类。

在此处查看http://jsfiddle.net/hbzqnrm8/5/

我希望它可以帮到你。

<button id="attack_enabled">ATTACK</button>
<button id="restore_enabled">RESTORE</button>

<div class="territory_middle_complete">ADD A CLASS HERE</div>

我已经编辑了你的jQuery代码,并添加了我认为你想要实现的东西。当然,如果你想在点击&#34;恢复&#34;时检查cookie的存在。按钮,如果没有,只需在任何需要的地方移动if条件,但不要在click函数之外移动,因为它只在加载文件时执行。

$("#attack_enabled").click(function(){
   createCookie('attackcompletecookie','attack_cookie');
});

$("#restore_enabled").click(function(){
   createCookie('restorecompletecookie','restore_cookie');
   var atkcomplete = readCookie('attackcompletecookie');
   if(atkcomplete)
   {
       alert(atkcomplete);
       $(".territory_middle_complete").addClass("displayblockzindex2");
    }
});

function createCookie(cookieName, cookieId) {
    document.cookie = cookieName + '=' + cookieId;
}

function readCookie(name) {
    var nameEQ = encodeURIComponent(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 decodeURIComponent(c.substring(nameEQ.length, c.length));
    }
    return null;
}