javascript - 基于页面标题/位置的重定向

标签 javascript redirect

我正在尝试将我的在线帮助重定向到手机版本。但是,我从单一来源生成电话和桌面版本,因此我希望有一段代码可以分别执行此操作(电话 <-769-> 桌面)。由于大小发生,我使用以下方法进行了重定向:

if (screen.width <= 769 || windowWidth <= 769) {
window.location = "../phone/Selecting_a_School_Register.htm";

但是当我在电话页面上时,它一直尝试加载页面(我明白为什么)。我自己尝试过,但我对此很陌生,这是我的(失败的)尝试:

windowWidth = window.innerWidth;
<!--
if (location.pathname = "/desktop/Selecting_a_School_Register.htm";) 
{
} else if (screen.width <= 769 || windowWidth <= 769) {
window.location = "../phone/Selecting_a_School_Register.htm";

}
</script><script>
if (location.pathname = "/phone/Selecting_a_School_Register.htm";) 
{
} else if (screen.width >= 769 || windowWidth >= 769) {
window.location = "../desktop/Selecting_a_School_Register.htm";

}

最佳答案

任何类型的条件语句都需要两个“==”,而不是像代码示例所示的单个“=”。另外,您的 if 语句中的字符串后面不需要分号。

比双等号更好的是三等号,即 strict comparison operator

试试这个:

windowWidth = window.innerWidth;

if (location.pathname === "/desktop/Selecting_a_School_Register.htm") {
} 
else if (screen.width <= 769 || windowWidth <= 769) {
    window.location = "../phone/Selecting_a_School_Register.htm";
}

if (location.pathname === "/phone/Selecting_a_School_Register.htm") {
} 
else if (screen.width >= 769 || windowWidth >= 769) {
    window.location = "../desktop/Selecting_a_School_Register.htm";
}

编辑:

此代码完全满足您的需要:

var pathname = window.location.pathname
  , width = window.innerWidth || document.documentElement.clientWidth || document.getElementsByTagName('body')[0].clientWidth;

if (width <= 769 && pathname !== '/mobile.html') {
    window.location = '/mobile.html';
}

if (width > 769 && pathname !== '/desktop.html') {
    window.location = '/desktop.html';
}

关于javascript - 基于页面标题/位置的重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19424931/

相关文章:

apache - .htaccess 301 重定向仅适用于谷歌机器人

wordpress - 从 HTTP 重定向到 HTTPS 会重复 www

php - 用于匹配 WP 重定向插件中不以字符串开头的 URL 的正则表达式

javascript - 如何在局部 View 中动态加载外部javascript?

javascript - 单击时处理输入值 React js

javascript - 如何在 JavaScript 或 Node.js 中创建用于 JSON 序列化的安全对象

javascript - AngularJS 未在 Firefox 中加载 View

带和不带 WWW 的 Apache 重定向 URL

vba - 将命令行过程的输出定向到 Excel

Javascript 信号量/测试和设置/锁定?