基于 URL 的重定向 - JavaScript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18022636/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Redirection based on URL - JavaScript
提问by Terri Eades
If someone types in 'www.morgancc.edu', I want it to redirect to our mobile site located at 'www.morgancc.edu/m' However, I only need to redirect with this exactURL. I don't want it to redirect if you go to something like 'www.morgancc.edu/programs', which is what it is currently doing. Here is the code I have so far:
如果有人输入“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>
采纳答案by mplungjan
location.hostname with an empty path is what you seem to want
带有空路径的位置.hostname 是您似乎想要的
if (window.location.hostname == "www.morgancc.edu" &&
window.location.pathname=="" ) {
window.location.href = 'http://www.morgancc.edu/m/';
}
Alternatively look at the href
或者看看href
if (window.location.href== "http://www.morgancc.edu") {
window.location.href = 'http://www.morgancc.edu/m/';
}
You may need to add some / here or there
您可能需要在这里或那里添加一些 /
回答by fred02138
The equality operator is ==
, not =
.
相等运算符是==
,不是=
。
回答by Moises Hidalgo
I suggest on using a sever-side scripting language to redirect base on the device visiting your site. you also have a typo in your if statement, you should have ==not =
我建议使用服务器端脚本语言根据访问您网站的设备进行重定向。你的 if 语句中也有错字,你应该有==not =
<script type="text/javascript">
if (window.location == "www.morgancc.edu") {
window.location.href = 'http://www.morgancc.edu/m/';
}
</script>