Cookie jquery隐藏和显示div

时间:2015-03-02 15:48:44

标签: javascript jquery cookies

我想使用我的javascript cookie让应用程序看看用户是否已登录..我在我的控制台中获取cookie的值..但每当我发表声明并想隐藏div时div不会做任何它没有显示或隐藏的事情..你能帮我吗?

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

}
function readCookie(name) {
   var i, c, ca, nameEQ = name + "=";
   ca = document.cookie.split(';');
   for(i=0;i < ca.length;i++) {
       c = ca[i];
       while (c.charAt(0)==' ') {
           c = c.substring(1,c.length);
       }
       if (c.indexOf(nameEQ) == 0) {
           return c.substring(name.length,c.length);
       }
   }
   return '';
} 

var user = readCookie('email');

if (!user) {
    document.getElementById('loginNav').style.display = 'block';
    document.getElementById('username').style.display = 'block';
    $("#loginNav").css("display","block");
}else{
    $("#loginNav").css("display","block");
   console.log( $("#loginNav").css("display","block"));

}

2 个答案:

答案 0 :(得分:0)

如果$('#loginNav').length == 0,那么您的元素尚未加载。

确保此代码位于jquery链接之后,并且包含在:

$(document).ready(function(){  
var user = readCookie('email');
  if (!user) {
        $('#loginNav, #username').show();
    }else{
        $("#loginNav, #username").hide();    
        //did you forget to hide the username?
    }
});

确保在HTML时代结束时加载所有JS文件。

答案 1 :(得分:0)

嗨设置&#34;显示&#34;财产到&#34;无&#34;隐藏....和&#34;阻止&#34;显示 我还会使用&#34; visibility&#34;:

if (!user) {
    $("#loginNav, #username").css("display","block");
    $("#username, #username").css("visibility","visible");
}else{
    $("#loginNav, #username").css("display","none");
    $("#username, #username").css("visibility","hidden");
}