在标签重定向后保持位置散列



我有一个静态网站,翻译数据,基于位置哈希(window.location.hash ==="#en")

不久以前,它只是一个页面的网站,但现在有更多的页面。当a tag重定向到其他页面时,位置散列消失。是否有一种方法来保持哈希所有的时间后的语言选择在重定向后的网址结束?

可能正如所说的那样,但是您需要考虑为什么需要它以及如何管理它。

您可以存储来自散列的语言以减少工作量,并最终得到这样的函数:

const getLocation = (language?: string | null): string => {
const hash = window.location.hash;
const location = localStorage.getItem("location");
language = language ?? hash ?? location;
if (language) {
localStorage.setItem("location", language);
return language;
}
if (hash) return getLocation(hash);
if (location) return getLocation(location);
// Default location if no hash or location is set
return getLocation("#en");
};
const actualLocation = getLocation();

当散列就位时,您的localStorage将被更新并跨页面可用。

最新更新