Multiple comparisons in an if statement using the

2020-02-06 13:20发布

I want to do he following, but it does not work:

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

It is completely ignoring my if statement and executes the code for all pages...

标签: javascript
5条回答
欢心
2楼-- · 2020-02-06 13:50

Try this:

if((pathname == '/ik/services/') || (pathname == '/ik/recruitment/')){
   //run function
}
查看更多
时光不老,我们不散
3楼-- · 2020-02-06 13:53

This has nothing to do with jQuery, it's just a normal JS "error". You need to compare both strings with the variable:

if (pathname == 'foo'  || pathname == 'bar') 
查看更多
The star\"
4楼-- · 2020-02-06 13:55

try doing

    if(pathname == '/ik/services/' || pathname == '/ik/recruitment/'){
      //run function
    }
查看更多
够拽才男人
5楼-- · 2020-02-06 13:58

Try

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

OR

jQuery inArray

Example

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

if($.inArray(pathname , arr) !== -1)
查看更多
疯言疯语
6楼-- · 2020-02-06 14:01

You would have to do something like this:

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

Your || '/ik/recruitment/' would always be truthy, and therfor the code within your if-statement will always run.

查看更多
登录 后发表回答