我有一个索引站点,用于检查cookie是否存在以及是否具有值EN
。如果是这样,它应该重定向到英语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存在(我使用JavaScript警告检查cookieValue
并显示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
,它会重定向到else
?
答案 0 :(得分:4)
if
后有一个正常的Javascript语句。
除非你把它放在else
中,否则没有任何迹象表明该声明不会运行。
导航到新页面不会终止当前页面的执行,直到新页面实际加载为止。
答案 1 :(得分: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>