Jquery Cookies代码在不进入索引页的情况下执行

Jquery Cookies代码在不进入索引页的情况下执行,jquery,cookies,Jquery,Cookies,请检查下面的代码 $(document).ready(function(){ var href; if(href!=null) { setContainerHtml($.cookie("activeElementHref")); }; $('nav ul li a').click(function(e){ e.preventDefault(); href= $(this).attr('href'); $.cookie("activeElementHref", href)

请检查下面的代码

$(document).ready(function(){
var href;
if(href!=null)
{
setContainerHtml($.cookie("activeElementHref"));
};

$('nav ul li a').click(function(e){
    e.preventDefault();
    href= $(this).attr('href');
    $.cookie("activeElementHref", href) 
    setContainerHtml(href);
});
}); 
function setContainerHtml(href) {
        $.ajax({
        type: "POST",
        url: "baker.php",
        data:{send_txt: href},
        success: function(data){
            $('#aside-right, #intro').css('display','none');
            $('#main-content').fadeOut('10', function (){
            $('#main-content').css('width','700px');
            $('#main-content').css('margin','-30px 0 0 100px');
            $('#main-content').html(data);
            $('#main-content').fadeIn('8000');
            });
        }   
    });
}
cookie不起作用。当我单击“刷新索引”html页面时,单击的链接状态未被保留。显示此代码:

    var href;
    href!='';
是真的,如果您使用Chrome,请转到控制台并执行它。因此,第一次调用setContainerHtml时

试试这个:

    var href;
    href!=null;

或者如果你真的想使用!=''只需输入var href=“”;在第一行中…

Href为null,而不是空字符串:

var href;  // variable is set to null...

if(href != '') // ... null is different than empty string...
{
    // ...so the code always enters here.
    setContainerHtml($.cookie("activeElementHref"));
};
我认为应该是:

var href = $.cookie("activeElementHref");  //Read the cookie

if(href !== null) 
{
    setContainerHtml(href );
};

似乎在DOM就绪时,
href
总是
null
,if语句
if(href!=null)
总是返回true。为什么不删除它呢?我编辑了我的代码,但是现在如果cookie状态没有保留,那么会发生什么呢?请从我的更新中删除代码。我想在检查状况之前你没有阅读cookie。它起作用了!现在如何在浏览器窗口关闭时删除cookie?我必须删除cookie,因为当我再次打开页面时,cookie保留状态页面已打开,而不是索引页面。您可以设置cookie过期时间。cookie将在该时间之后被删除。我编辑了代码,但现在如果cookie状态未保留,会发生什么情况?您在哪里读取cookie?尝试以下操作:var href=$.cookie(“activeElementHref”)//读取cookie if(href!=null)//检查cookie是否存在{if(href!=“”)//检查其是否为空?也许您可以忽略它{setContainerHtml(href);};};