Javascript 三、索引不匹配-返回另一个结果

Javascript 三、索引不匹配-返回另一个结果,javascript,jquery,Javascript,Jquery,我有一个基于移动设备操作系统的重定向。 我尝试在下面的脚本中返回重定向 $(document).ready(function (){ //Android Version: if(navigator.userAgent.toLowerCase().indexOf("android") != -1) { window.location.href = "https://link1"; } if(navigator.userAgent.toLowerCase().indexOf("iphone") !=

我有一个基于移动设备操作系统的重定向。 我尝试在下面的脚本中返回重定向

$(document).ready(function (){
//Android Version:
if(navigator.userAgent.toLowerCase().indexOf("android") != -1) {
window.location.href = "https://link1";
}
if(navigator.userAgent.toLowerCase().indexOf("iphone") != -1){
window.location.href = 'https://link2';
}

if(navigator.userAgent.toLowerCase().indexOf("ipad") != -1){
window.location.href = 'https://link3';
}
});
我需要第四个重定向,如果以上都不是真的。但当我在脚本末尾使用时:

 else {
window.location.href = 'https://link4';
}

只有ipad重定向才有效。Iphone和android重定向到link4。

您需要在所有后续的
if
s上使用
else
。因此:

$(document).ready(function (){
    //Android Version:
    if(navigator.userAgent.toLowerCase().indexOf("android") != -1) {
        window.location.href = "https://link1";
    } else if(navigator.userAgent.toLowerCase().indexOf("iphone") != -1){
// ---^^^^
        window.location.href = 'https://link2';
    } else if(navigator.userAgent.toLowerCase().indexOf("ipad") != -1){
// ---^^^^
        window.location.href = 'https://link3';
    } else {
        window.location.href = 'https://link4';
    }
});
这样,如果第一个
if
的条件为true,则只执行
if
块中的操作。如果第一个
If
的条件为false,则执行下一个
If
,如果为true,则只执行其
If
块中的操作
。如果
If
条件均为true,则最后执行
else`块

以上是编写它的标准方式,但这种冗长的方式可能有助于使它更清晰:

$(document).ready(function (){
    //Android Version:
    if(navigator.userAgent.toLowerCase().indexOf("android") != -1) {
        window.location.href = "https://link1";
    } else {
        if(navigator.userAgent.toLowerCase().indexOf("iphone") != -1){
            window.location.href = 'https://link2';
        } else {
            if(navigator.userAgent.toLowerCase().indexOf("ipad") != -1){
                window.location.href = 'https://link3';
            } else {
                window.location.href = 'https://link4';
            }
        }
    }
});

这与我上面的第一个代码块所做的事情完全相同。

每个
if
语句后面都需要一个
else if
,因此,不是三个单独的
if
语句,最后一个语句有一个
else
,而是一个带有多个条件的
if
语句

$(document).ready(function (){
  //Android Version:
  if(navigator.userAgent.toLowerCase().indexOf("android") != -1) {
    window.location.href = "https://link1";
  } else if(navigator.userAgent.toLowerCase().indexOf("iphone") != -1){
    window.location.href = 'https://link2';
  } else if(navigator.userAgent.toLowerCase().indexOf("ipad") != -1){
    window.location.href = 'https://link3';
  } else {
    window.location.href = 'https://link4';
  }
});
“最佳实践传道者(除非我心情懒散)”