我知道这是一个被广泛讨论的问题,但我不明白为什么它对我不起作用。
这是我的职责:
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 = "/comments.aspx?id=" + movieShareId.textContent || movieShareId.innerText + "/";
到
window.location = "/comments.aspx?id=" + (movieShareId.textContent || movieShareId.innerText) + "/";
与
||
相比,+
没有优先权。
同时删除
window.location
赋值之后的所有内容:此代码不应在页面更改时执行。
注意:您不需要设置
location.href
。只需设置location
就足够了。
解决方案来自这里: http://www.codeproject.com/Questions/727493/JavaScript-document-location-href-not-working
document.location.href = 'Your url',true;
确保您没有在网址末尾发送“#”。就我而言,这导致 window.location.href 无法工作。
您不能使用
window.location.replace
或 document.location.href
或任何您最喜欢的普通 javascript 方法将页面重定向到其自身。
因此,如果您从后端动态添加重定向路径,或从数据标记中提取重定向路径,请确保在某个阶段检查是否重定向到当前页面。它可以很简单:
if(window.location.href == linkout)
{
location.reload();
}
else
{
window.location.href = linkout;
}
我将为您提供一个解决此问题的好函数:
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.replace
是模拟重定向的最佳方式:
function ShowComments(){
var movieShareId = document.getElementById('movieId');
window.location.replace("/comments.aspx?id=" + (movieShareId.textContent || movieShareId.innerText) + "/");
}
有关为什么
window.location.replace
是最好的 JavaScript 重定向的更多信息可以在 在这里找到。
就我而言,设置时间间隔后,它对所有浏览器都按预期工作。
setTimeout(function(){document.location.href = "myNextPage.html";},100);
window.location.href 在 Android 中不起作用。 我清除了 Android Chrome 中的缓存,它工作正常。 建议在参与各种编码之前先尝试一下。
转到您的 api 路由,确保您没有错过诸如
之类的响应res.status(200).json(data);
我遇到了同样的问题,我使用以下方法解决了它:
setTimeout(function () {
document.location.href = '../html/home-page.html';
}, 100);
Aijaj 编写了相同的解决方案,但多了一个分号,这导致我花费了大量时间进行调试 😅