javascript window.location.replace(href); 后退按钮失败;

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11844430/
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-26 14:32:01  来源:igfitidea点击:

Back button fails after window.location.replace(href);

javascriptjqueryfirefoxgoogle-chromeopera

提问by sznowicki

I made simple function which makes all container behave like link ("a" element).

我做了一个简单的函数,使所有容器的行为都像链接(“a”元素)。

function allHot(element){
$(element)
.click(
    function(){
    var href = $(this).find('a').attr('href');
    window.location.replace(href);
})

.hover(
    function(){
    $(this).css({'text-shadow' : '0px 1px 0px #D6D6D6'});
    },
    function(){
    $(this).css({'text-shadow' : 'none'});
    }

);
}

Function works great. Instead of clicking the "more" button, user can click everywhere on container and is properly redirected.

功能很好用。用户无需单击“更多”按钮,而是可以单击容器上的任何位置并正确重定向。

However, if user after redirection clicks back button, browser goes back two steps instead of one as it should. What's more weird, history looks OK.

但是,如果用户在重定向后单击后退按钮,浏览器将返回两步而不是它应该的一步。更奇怪的是,历史看起来还不错。

Simple scheme to better description:

更好描述的简单方案:

Page1 -> Page2

Page2 [user clicks on "allHot" container] -> allHot redirects to Page3

Page3 [user clicks on browser back button] -> Page1

第1页->第2页

Page2 [用户点击“allHot”容器] -> allHot 重定向到 Page3

Page3 [用户点击浏览器后退按钮] -> Page1

This is major bug for website I'm working on right now. I don't really have a clue to prevent it. Bug tested on Firefox, Chrome and Opera.

这是我现在正在处理的网站的主要错误。我真的没有任何线索可以阻止它。在 Firefox、Chrome 和 Opera 上测试了错误。

Tested also on Opera "no javascript mode". If javascript is disabled issue doesn't occure.

也在 Opera“无 javascript 模式”上进行了测试。如果 javascript 被禁用,则不会发生问题。

Thanks in advance for any clue or solution.

在此先感谢您提供任何线索或解决方案。

回答by MarcoK

Instead of using replace, use the following:

不要使用replace,而是使用以下内容:

window.location.href = ''

回答by Carlos Calla

Adding to MarcoK's answer.

添加到 MarcoK 的答案中。

When using replaceyou are replacing the history state so you are not pushing one more state to the history.

使用时,replace您正在替换历史状态,因此您不会再将一个状态推送到历史中。

If you have the following:

如果您有以下情况:

Page1to State1

Page1State1

Page2to State2

Page2State2

and then you use replace you will be replacing Page3to State2.

然后你使用 replace 你将替换Page3State2.

When you press the back button you will go from State2to State1and that is why you are going to Page1.

当您按下后退按钮时,您将从State2State1,这就是您要去的原因Page1

When using window.location.hrefyou are adding one more state so Page3will be set to State3and when you click the back button you will go to State2wich has Page2as URL.

使用时,window.location.hrefPage3将再添加一个状态,因此将设置为State3,当您单击后退按钮时,您将转到State2具有Page2URL 的位置。