Javascript document.location 重定向到错误的 url
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17588166/
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
Javascript document.location redirect to a wrong url
提问by Snippet
I use this following code to redirect if site was visited on mobile devices
如果在移动设备上访问了站点,我将使用以下代码进行重定向
<script type="text/javascript">
<!--
if (screen.width <= 978) {
document.location = "mobile.mysite.com";
}
//-->
</script>
I tested it on many devices. Why does the site redirects to www.mysite.com/mobile.mysite.com
instead of mobile.mysite.com
only?
我在许多设备上对其进行了测试。为什么该站点重定向到www.mysite.com/mobile.mysite.com
而不是mobile.mysite.com
仅?
回答by Adils Adils
Try this thing
试试这个
<script type="text/javascript">
<!--
if (screen.width <= 978) {
document.location.href = "http://mobile.mysite.com";
}
//-->
</script>
回答by Andy E
You need to specify 'http://'
or just '//'
at the beginning, otherwise the URL is treated as relative instead of absolute.
您需要在开头指定'http://'
或'//'
,否则 URL 将被视为相对而不是绝对。
if (screen.width <= 978) {
document.location.href = "//mobile.mysite.com";
}
回答by Gintas K
try using window.location.href
instead of document.location
:)
尝试使用window.location.href
而不是document.location
:)