【问题标题】:Trigger a window.alert with the if and return true使用 if 触发 window.alert 并返回 true
【发布时间】:2018-05-10 17:29:19
【问题描述】:

现在,当谈到 Javascript 时,我完全是个菜鸟,所以这可能真的很容易,但是; 我在 Stack Overflow 上的其他地方找到了这段代码,该代码应该检测网页中加载的设备是否是移动设备。我想要做的只是能够从中获取值并触发 window.alert 消息,告诉他们进入横向模式。

 <script language="JavaScript" type="text/javascript">
          function detectmob() {
      if( navigator.userAgent.match(/Android/i)
      || navigator.userAgent.match(/webOS/i)
      || navigator.userAgent.match(/iPhone/i)
      || navigator.userAgent.match(/iPad/i)
      || navigator.userAgent.match(/iPod/i)
      || navigator.userAgent.match(/BlackBerry/i)
      || navigator.userAgent.match(/Windows Phone/i)
      ){
      return true;
      }
      else {
      return false;
      }
    }
    </script>
  </head>
  <body onload="detectmob()">

【问题讨论】:

  • 去掉两个return 语句并用适当的alert() 语句替换它们。并且,考虑完全不这样做并使用 CSS 媒体查询来创建响应式网页设计,因为 navigator.userAgent 不可靠。
  • 请不要。没有什么(几乎)比网页比我更了解我应该如何握住手机更烦人......
  • 另外(仅供参考),您可以从代码中删除 language="JavaScript" type="text/javascript"。这在 HTML 的最后一个版本中是必需的,但 5 年多以来就不再需要了。
  • @ScottMarcus 感谢您的快速帮助!回想起来要容易得多,我最终必须在 JS 中做一些认真的练习。 ;D

标签: javascript html triggers


【解决方案1】:

在此处删除您的 return 语句,您不需要它们。如果 if 条件为真,只需触发alert

function detectmob() {
  if (navigator.userAgent.match(/Android/i) ||
    navigator.userAgent.match(/webOS/i) ||
    navigator.userAgent.match(/iPhone/i) ||
    navigator.userAgent.match(/iPad/i) ||
    navigator.userAgent.match(/iPod/i) ||
    navigator.userAgent.match(/BlackBerry/i) ||
    navigator.userAgent.match(/Windows Phone/i)
  ) {
    alert("Please put your phone into landscape mode.");
  } else {
    console.log("Desktop user.");
  }
}
&lt;body onload="detectmob()"&gt;

【讨论】:

    猜你喜欢
    • 2016-02-12
    • 2013-03-21
    • 1970-01-01
    • 2019-03-29
    • 2016-01-04
    • 2016-11-14
    • 2020-04-19
    • 1970-01-01
    • 2015-12-16
    相关资源
    最近更新 更多