gpt4 book ai didi

javascript - history.back() 不会在 Chrome/FireFox 中更新 location.hash

转载 作者:数据小太阳 更新时间:2023-10-29 04:51:38 27 4
gpt4 key购买 nike

我尝试构建一个 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;
}

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

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

有什么变通办法吗?

最佳答案

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) 中需要多少步。

关于javascript - history.back() 不会在 Chrome/FireFox 中更新 location.hash,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8319533/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com