0

我有一个索引站点,它检查 cookie 是否存在以及它是否具有 value EN。如果是这样,它应该重定向到 English index.shtml。否则,或者如果没有(英语)cookie,它应该重定向到德语下一页:

if (document.cookie)  {
    var cookieValue = document.cookie;
    if (cookieValue.indexOf("MYCOOKIE=EN") > -1)  {
        window.location.href="en/index.shtml";
    }
}
window.location.href="kategorien/hauptkategorie.shtml";

现在发生了一些非常奇怪的事情:英文cookie存在(我检查cookieValue了JavaScript警报并显示EN),但即使if不会执行内部的href,但会执行第二个href。为什么会这样?

当我添加 2 时else,它的工作方式与预期一样:

if (document.cookie)  {
     var cookieValue = document.cookie;
     if (cookieValue.indexOf("MYCOOKIE=EN") > -1)  {
         window.location.href="en/index.shtml";
     }
     else  {
         window.location.href="kategorien/hauptkategorie.shtml";
     }
}
else  {
     window.location.href="kategorien/hauptkategorie.shtml";
}

hauptkategorie.shtml为什么如果我离开s ,它会重定向到else

4

2 回答 2

4

之后有一个正常的 Javascript 语句if

没有什么告诉该语句不要运行,除非你把它放在一个else.

在新页面实际加载之前,导航到新页面不会终止当前页面的执行。

于 2011-10-30T21:14:41.527 回答
3

可能这两个window.location.href语句都会执行,给您带来意想不到的结果。尝试类似:

<script type="text/javascript"> 
if (document.cookie && document.cookie.indexOf("MYCOOKIE=EN") > -1)  {
    window.location.href="en/index.shtml";  
}
else {
    window.location.href="kategorien/hauptkategorie.shtml";
}
</script>
于 2011-10-30T21:22:50.027 回答