Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/84.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在移动设备上重定向*仅适用于*存在特定锚的情况?(我的当前代码重定向但忽略条件)_Javascript_Jquery_If Statement_Redirect_Mobile - Fatal编程技术网

Javascript 在移动设备上重定向*仅适用于*存在特定锚的情况?(我的当前代码重定向但忽略条件)

Javascript 在移动设备上重定向*仅适用于*存在特定锚的情况?(我的当前代码重定向但忽略条件),javascript,jquery,if-statement,redirect,mobile,Javascript,Jquery,If Statement,Redirect,Mobile,在手机上,只有当url为website.com/#store时,我才会重定向到子域store.website.com。如果url不是那样,我会重定向到子域m.website.com。如果url仅为website.com,则以下内容始终重定向到存储子域,无论是否为存储锚定: var url = "http://website.com/#store"; var hash = url.substring(url.indexOf("#")+1); if (hash == "store") { windo

在手机上,只有当url为
website.com/#store
时,我才会重定向到子域
store.website.com
。如果url不是那样,我会重定向到子域
m.website.com
。如果url仅为
website.com
,则以下内容始终重定向到存储子域,无论是否为存储锚定:

var url = "http://website.com/#store";
var hash = url.substring(url.indexOf("#")+1);
if (hash == "store") {
window.location.replace("http://store.website.com");
} else if (window.location.href == "http://website.com") {
window.location.replace("http://m.website.com");
} 

如果我用一个简单的“else”语句替换“else if”语句,或者完全删除else语句,则会得到相同的结果。在任何情况下,它总是重定向到
store.website.com
。我是否应该在这里做一些轻微的调整,以使代码按预期的方式工作,或者可能是一种完全不同的方法来完成这个任务?谢谢

在上面的代码中,您总是在更新位置,因为
哈希
总是等于
'store'
。如果,则永远无法到达第二个


也许您应该从
window.location.href
读取散列,而不是变量
url

这个小脚本可以:

var hash=window.location.hash

散列和散列==“#存储”?window.location.replace(“http://store.website.com“”:window.location.replace(“”)http://m.website.com“”
您的URL始终是一个固定字符串。您应该检查window.location.href

var url = window.location.href;
var hash = url.substring(url.indexOf("#")+1);
if (hash == "store") {
window.location.replace("http://store.website.com");
} else if (url == "http://website.com") {
window.location.replace("http://m.website.com");
} 

这是因为变量
url
总是设置为
http://website.com/#store

var url = "http://website.com/#store";
将此更改为:

var url = window.location.href;
window.location.href
将检索当前地址。那么散列应该是正确的

或者使用
location.hash
来学习此代码:

var hash = window.location.hash;

if (hash == "#store")
{
    window.location.replace("http://store.website.com");
}
else if (window.location.hostname == "website.com")
{
    window.location.replace("http://m.website.com");
}
首先,我们使用
window.location.hash
获取散列部分并进行匹配。如果未通过,请检查主机名。不要使用完整的url。如果有人使用HTTPS而不是HTTP进入,它将不会通过。因此,使用
window.location.hostname
来匹配域名


请注意,此代码不仅会影响移动设备,除非您检查是否使用了移动设备,否则桌面用户也将被重定向到
m.website.com

旁注
window.location.hash
将返回
#store