基于URL的重定向 - JavaScript

7

如果有人输入“www.morgancc.edu”,我希望它重定向到我们的移动站点“www.morgancc.edu/m”。然而,我只需要使用这个确切的URL进行重定向。如果您访问类似于“www.morgancc.edu/programs”的页面,我不希望它重定向到移动站点,但是目前它正在执行此操作。以下是我目前拥有的代码:

<script type="text/javascript">
if (window.location = "www.morgancc.edu") {
   window.location.href = 'http://www.morgancc.edu/m/'; 
}
</script>
3个回答

9

location.hostname和空路径是您需要的内容。

if (window.location.hostname == "www.morgancc.edu" && 
    window.location.pathname=="" ) {
   window.location.href = 'http://www.morgancc.edu/m/'; 
}

或者查看 href

if (window.location.href== "http://www.morgancc.edu") {
   window.location.href = 'http://www.morgancc.edu/m/'; 
}

您可能需要在这里或那里添加一些 / 。

对于我正在做的事情来说是有意义的。然而,现在它根本不会重定向。 - Terri Eades
你的第二个建议起作用了!这是我使用的代码:'<script type="text/javascript"> if (window.location.href == "http://www.morgancc.edu/" ) { window.location.href = 'http://www.morgancc.edu/m/'; } </script>' - Terri Eades

9
等值运算符是 ==,而不是 =

6

我建议使用服务器端脚本语言根据访问您网站的设备进行重定向。另外,您的 if 语句中存在拼写错误,应该使用 == 而不是 =

<script type="text/javascript">
if (window.location == "www.morgancc.edu") {
   window.location.href = 'http://www.morgancc.edu/m/'; 
}
</script>

在我的博客网站上使用这段代码。完美运行。 - zmd94

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接