history.back()不会更新Chrome/FireFox中的location.hash

Rad*_*094 7 javascript firefox google-chrome

我尝试构建一个可以更改页面位置的JS脚本,直到找到特定的哈希位置:

var StopAtThisHash ='#';
var CurrentHash = window.location.hash;
var continueLoop = true;
while ((window.history.length>0) && (continueLoop))
{
        window.history.back();
        var NowWeAreAtHash = window.location.hash; //this never changes in Chrome
        //actually, always seems to:  CurrentHash  == NowWeAreAtHash;
       if(NowWeAreAtHash == StopAtThisHash)
                        continueLoop= false;
}
Run Code Online (Sandbox Code Playgroud)

很奇怪,在Chrome和FF中,window.location.hash在back()之后没有改变.历史长度也没有像我预期的那样减少1.循环无限运行,浏览器挂起.

在IE 9中,这似乎按预期运行.

有没有解决方法呢?

the*_*bas 0

看起来window.history.back()window.history.forward()window.history.go()没有改变历史,只是来回导航。如果back()要改变历史的长度那么你将无法做到forward()

作为解决方法,我建议使用window.historyfor最后到第一个循环而不是while.