Javascript window.location.href.indexOf 是 A 而不是 B

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14470836/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 21:42:42  来源:igfitidea点击:

Javascript window.location.href.indexOf is A and not B

javascript

提问by Ivo

I'm using the following to do somting when url contains gender=men&dir=

当 url 包含 sex=men&dir= 时,我使用以下内容进行 somting

if(window.location.href.indexOf("gender=men&dir=") > -1) {

      }

Now i need to say url contains gender=men&dir= and not &dir=Schoenen do something

现在我需要说 url 包含性别=men&dir= 而不是 &dir=Schoenen 做某事

i was trying this only its not working

我正在尝试这只是它不起作用

if(window.location.href.indexOf("gender=men&dir=" || !"&dir=Schoenen") > -1) {

      }

回答by Joseph Silber

You have to call indexOftwice:

你必须调用indexOf两次:

var hasGender = window.location.href.indexOf("gender=men&dir=") != -1;
var hasDir = window.location.href.indexOf("&dir=Schoenen") != -1;

if ( hasGender && ! hasDir ) {
    // Do whatever you want...
}

回答by Tom

||can't be used that way.

||不能这样使用。

You need to state the window.location.href.indexOftwice:

您需要说明window.location.href.indexOf两次:

if (window.location.href.indexOf("gender=men&dir=") > -1) &&
    window.location.href.indexOf("&dir=Schoenen") == -1) {

}

// > -1 is if found
// == -1 is if not found

If you want to change the AND (&&) into an OR (||), you'll need to replace &&into ||.

如果要将 AND ( &&)更改为 OR ( ||),则需要替换&&||