javascript - 设置 cookie 并在多次访问时重定向未按预期工作
问题描述
我创建了一个脚本,在我看来应该可以工作,但不幸的是,即使满足条件,它也设置了 cookie2 的问题。
<script type="text/javascript">
jQuery(document).ready(function () {
if (typeof Cookies.get('cookie1') !== 'undefined') {
Cookies.set('cookie2', 'true', {expires: 1000});
window.location.href = "https://google.com/second";
}
else
{
Cookies.set('cookie1', 'true', {expires: 1000});
}
window.location.href = "https://google.com/first";
}
});
</script>
<script type="text/javascript">
jQuery(document).ready(function () {
if (typeof Cookies.get('cookie2') !== 'undefined') {
window.location.href = "https://google.com/third";
}
else
{
}
});
</script>
用户第一次访问应该访问 google.com/first,用户第二次访问应该访问 google.com/second,最后一次访问应该访问 google.com/third。第二次访问没有得到满足,因为看起来像 cookie 2 已经被插入,即使它不在第一个“else”函数中
解决方案
嗨,问题在于您的 if/else 条件的条件说明。它将始终进入 else 条件,因为在第一页加载后为cookie1设置了该值
window.location.href = " https://google.com/first ";
所以你需要添加嵌套的 if/else 条件
小提琴链接:https ://jsfiddle.net/kju86Ly9/3/
jQuery(document).ready(function () {
console.log(getCookie('cookie1'))
console.log(getCookie('cookie2'))
if (getCookie('cookie1') !== 'undefined' && getCookie('cookie2') === null) {
setCookie('cookie2', 'true', 10);
console.log('https://google.com/first')
window.location.href = "https://google.com/first";
} else if (getCookie('cookie2') !== 'undefined' && getCookie('cookie3') === null) {
setCookie('cookie3', 'true', 10);
console.log('https://google.com/second')
window.location.href = "https://google.com/second";
} else {
console.log('https://google.com/third')
window.location.href = "https://google.com/third";
}
function setCookie(name, value, days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
function getCookie(name) {
var nameEQ = 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 c.substring(nameEQ.length, c.length);
}
return null;
}
function eraseCookie(name) {
document.cookie = name+'=; Max-Age=-99999999;';
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
推荐阅读
- javascript - Javascript:当我使用相同的代码但在函数之外它可以工作
- python - 停止词清理与列表理解
- python - 如何在 tkinter 的 Notebook 中切换选项卡时随机停止选项卡的内容闪烁
- c# - 在 3D 视图中时,PointerMoved 事件未在 MapControl 上触发
- python - python从Max接收OSC消息
- java - 如何使用 Java 中的 if 语句检查字符串是否为空或 null?
- c# - 为不同的日历获取一年中某一天的更好方法
- java - ESP32 与 java 本地服务器之间的 Socket 通信
- reactjs - 苹果硅 + CRA
- javascript - 点击元素后触发点击