设置 cookie 并在多次访问时重定向未按预期工作

Set cookie and redirect on multiple visits not working as intended

我创建了一个脚本,我认为它应该可以工作,但不幸的是,即使满足条件,它也会设置 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条件

Fiddle link :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>