javascript - 三个 .indexOf 不匹配 - 返回另一个结果

标签 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") != -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 语句后面都需要一个 else if,这样就可以代替 3 个单独的 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';
  }
});

关于javascript - 三个 .indexOf 不匹配 - 返回另一个结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59238593/

相关文章:

javascript - 尝试制作 HTML 表格并使用相同的 JSON 数据填充选择标签

javascript - 禁用按钮,直到达到一个数字

javascript - 如何避免重复渲染 React 组件?

javascript - dc.js:堆叠条形图无法显示

javascript - 点击时隐藏一个div并显示另一个直到最后

javascript - 使用 JQuery/Javascript 将文本插入到 html div 表的特定单元格中?

javascript循环遍历多个条件

javascript - Meteor:将复选框(作为 bool 值)插入到子架构中 (aldeed2)

javascript - 防止自动建议提交表单

javascript - jQuery UI 扩展可拖动 "Snap"行