简体   繁体   English

如何正确嵌套If / Else语句?

[英]How to properly nest an If/Else statement?

I am trying to set multiple cookies. 我正在尝试设置多个Cookie。 if a specific cookie exists another one is set. 如果存在特定的cookie,则设置另一个cookie。 ie if cookie "1" exists i set cookie"2" and if cookie 2 exists i set cookie "3" and so on. 即,如果存在cookie“ 1”,则将cookie设置为“ 2”,如果存在cookie 2,则将cookie设置为“ 3”,依此类推。

i am trying to achieve that with an if/else statement which i couldn't get to work. 我试图通过if / else语句来实现这一点,但我无法上班。

if(getCookie('1')) {
    setCookie('2',1,365);
} else {
    if(getCookie('2')) {
        setCookie('3',1,365);
    } else {
        if(getCookie('3')) {
            setCookie('4',1,365);
        } else {
            if(getCookie('4')) {
                setCookie('5',1,365);
            } else {
                setCookie('1',1,365);
            }
        }
    }
}

What i want to achieve is show different messages for a returning visitors to my site. 我要实现的目标是为回访者显示不同的消息。 not just for the 1st time visit but until their 10th visit . 不仅是第一次访问,直到他们第10次访问。

It would be easier if you use a loop. 如果使用循环会更容易。 Interate through the desired values, and if it exists, you add it +1... If none is set, the default one is applied... 遍历所需的值,如果存在,则将其加+1 ...如果未设置,则应用默认值...

var cookieToSet = "1";
for(var i=1; i<=4; i++) {
    if(getCookie(i)) {
        cookieToSet = i+1;
        break;
    }
}
setCookie(cookieToSet', 1, 365);

try this : 尝试这个 :

if(getCookie('1'))
    {
    setCookie('2',1,365);
    }else if(getCookie('2'))
    {
        setCookie('3',1,365);
     }else if(getCookie('3'))
     {
            setCookie('4',1,365);
     }else if(getCookie('4'))
     {
          setCookie('5',1,365);
      }else
      {
           setCookie('1',1,365);
      }

or else use switch case for it , hope it will work for you !! 否则使用开关盒,希望它能为您服务!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM