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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 08:53:53  来源:igfitidea点击:

Javascript document.location redirect to a wrong url

javascriptredirect

提问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.cominstead of mobile.mysite.comonly?

我在许多设备上对其进行了测试。为什么该站点重定向到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.hrefinstead of document.location:)

尝试使用window.location.href而不是document.location:)