2011-11-30 111 views
7

更新的location.hash我试图建立一个JS脚本,将改变页面的位置,要回去,直到一个特定的散列位置中找到:history.back()不会在Chrome /火狐

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; 
} 

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

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

任何解决方法?

+0

也许看看这个http://stackoverflow.com/questions/2305069/can-you-use-hash-navigation-without-affecting-history,因为你可以使用'history.replaceState(undefined,undefined,“#hash_value “)'来替换散列值 – Hendry

回答

0

似乎是window.history.back(),window.history.forward()window.history.go()不改变历史,只是来回导航。如果back()会改变历史的长度,那么你将无法forward()

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

0
function goBackHome() { 
    goBackToHash(''); // Assume the home is without hash. You can use '#'. 
} 
function goBackToHash(hash) { 
    setTimeout(function() { 
     if (window.location.hash == hash) return; 
     history.back(); 
     goBackToHash(hash); 
    }, 0); 
} 

为了克服while循环的问题,我尝试使用setTimeout,但这通常是更进了一步比预期...等待一个完美的解决方案。

我认为在history.back()window.location.hash被更改之间存在延迟。

另一个解决方法是在JS中保留散列值,以便您可以计算出history.go(N)需要多少步骤。