使用逻辑OR运算符在if语句中进行多次比较

时间:2013-04-09 11:55:27

标签: javascript

我想跟随他,但它不起作用:

if(pathname == '/ik/services/' || '/ik/recruitment/'){
   //run function
}

它完全忽略了我的if语句并执行了所有页面的代码......

5 个答案:

答案 0 :(得分:7)

你必须做这样的事情:

if(pathname == '/ik/services/' || pathname == '/ik/recruitment/'){
   //run function
}

您的|| '/ik/recruitment/'始终为truthy,而且if语句中的代码将始终运行。

答案 1 :(得分:4)

尝试

if(pathname == '/ik/services/' || pathname == '/ik/recruitment/'){

jQuery inArray

示例

var arr = ['/ik/services/','/ik/recruitment/'];

if($.inArray(pathname , arr) !== -1)

答案 2 :(得分:2)

这与jQuery无关,它只是一个普通的JS“错误”。您需要将两个字符串与变量进行比较:

if (pathname == 'foo'  || pathname == 'bar') 

答案 3 :(得分:1)

试试这个:

if((pathname == '/ik/services/') || (pathname == '/ik/recruitment/')){
   //run function
}

答案 4 :(得分:1)

尝试做

    if(pathname == '/ik/services/' || pathname == '/ik/recruitment/'){
      //run function
    }