嵌套条件语句(如果,再次切换)

时间:2012-01-25 22:33:38

标签: javascript jquery

快速提问:这种嵌套可能吗? if语句首先传递一个开关然后再传递另一个if语句,这样它就不会影响其他未在switch上捕获的值?

var cookie = ""; //some value previously setted by filtering a cookie, like a product id
var prod = "";
var img = "";
if ((cookie != null) && (prod != '')) {
    switch (cookie) {
    case '001': case '002': case '003':
        prod = "Product01";
        img = "product01.jpg"
        break;
    case '004': case '005': case '006':
        prod = "Product02";
        img = "product02.jpg"
        break;
    case '007': case '008':
        prod = "Product03";
        img = "product03.jpg"
        break;
    case 'null':
        break;
    }
    if (window.location.pathname == 'somepage') {
        //jQuery code
    } else if (window.location.pathname == 'anotherpage') {
        //jQuery code
    } else {
        //jQuery code
    }
}

1 个答案:

答案 0 :(得分:1)

是的。 你可以写点像

if (condition){
    switch(n)
    {
    case 1:
      execute code block 1
      break;
    case 2:
      execute code block 2
      break;
    default:
      code to be executed if n is different from case 1 and 2
    }
}

以及

    switch(n)
    {
    case 1:
      if (condition)
        {
        code to be executed if condition is true
        }
      break;
    case 2:
      execute code block 2
      break;
    default:
      code to be executed if n is different from case 1 and 2
    }

..好吧,我不会展示所有案例......

只需查看http://www.w3schools.com/js/js_switch.asphttp://www.w3schools.com/js/js_if_else.asp,您就可以找到有关else语句的更多详细信息。正如有人在评论中感到悲伤:试试吧! 通常这是理解的最佳方式。