繁体   English   中英

window.location.href 不重定向

[英]window.location.href doesn't redirect

我知道这是一个经常讨论的问题,但我不明白为什么它对我不起作用。

这是我的功能:

function ShowComments(){

 alert("fired");
 var movieShareId = document.getElementById('movieId');
 //alert("found div" + movieShareId.textContent || movieShareId.innerText);
 //alert("redirect location: /comments.aspx?id=" + movieShareId.textContent || movieShareId.innerText + "/");
 window.location.href = "/comments.aspx?id=" + movieShareId.textContent || movieShareId.innerText + "/";
 var newLocation = window.location;
 //alert("full location: " + window.location);

}

如果我没有注释警告或者如果我打开了 Mozilla 的 bugzilla 它工作正常,否则它不会重定向到另一个页面。

任何想法为什么?

如果您通过提交按钮调用此函数。 这可能是浏览器不重定向的原因。 它将运行函数中的代码,然后提交页面而不是重定向。 在这种情况下,请更改按钮的类型标签。

从这个答案,

window.location.href 不起作用

你只需要添加

return false;

在函数的底部

来自这里的解决方案: http : //www.codeproject.com/Questions/727493/JavaScript-document-location-href-not-working

document.location.href = 'Your url',true;

缺少一些括号。

改变

 window.location.href = "/comments.aspx?id=" + movieShareId.textContent || movieShareId.innerText + "/";

 window.location = "/comments.aspx?id=" + (movieShareId.textContent || movieShareId.innerText) + "/";

||没有优先权+相比。

window.location分配之后也删除所有内容:不应在页面更改时执行此代码。

注意:您不需要设置location.href 只需设置location就足够了。

确保您没有在 URL 末尾发送“#”。 就我而言,这会阻止 window.location.href 工作。

window.location.replace是模拟重定向的最佳方式:

function ShowComments(){
    var movieShareId = document.getElementById('movieId');
    window.location.replace("/comments.aspx?id=" + (movieShareId.textContent || movieShareId.innerText) + "/");
}

更多关于window.location.replace为什么是最好的 javascript 重定向的信息可以在这里找到。

我会给你一个很好的函数来解决这个问题:

function url_redirect(url){
    var X = setTimeout(function(){
        window.location.replace(url);
        return true;
    },300);

    if( window.location = url ){
        clearTimeout(X);
        return true;
    } else {
        if( window.location.href = url ){
            clearTimeout(X);
            return true;
        }else{
            clearTimeout(X);
            window.location.replace(url);
            return true;
        }
    }
    return false;
};

这是window.location问题的通用解决方案。 有些浏览器进入有问题的window.location.href和有时也可能发生window.location失败。 这就是为什么我们还在任何情况下使用window.location.replace()并为“最后一次尝试”使用超时。

您不能使用window.location.replacedocument.location.href或任何您喜欢的 vanilla javascript 方法将页面重定向到它自己

因此,如果您从后端动态添加重定向路径,或从数据标记中提取它,请确保在某个阶段检查重定向到当前页面。 它可以很简单:

if(window.location.href == linkout)
{
    location.reload();
}
else
{
    window.location.href = linkout;
}

在我的情况下,它在设置时间间隔后对所有浏览器都按预期工作。

setTimeout(function(){document.location.href = "myNextPage.html;"},100);

window.location.href 在 Android 中不起作用。 我清除了 Android Chrome 中的缓存,它工作正常。 建议在参与各种编码之前先尝试这个。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM