Javascript 可以替换window.location.hash吗?

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

possible to replace window.location.hash?

javascriptjquerywindow.location

提问by circey

I'm wondering whether it's possible to change the hash in window.location.hash and replace it with 'this.id'. Or would I need to change the entire window.location?

我想知道是否可以更改 window.location.hash 中的哈希值并将其替换为“this.id”。还是我需要更改整个 window.location?

回答by BoltClock

Yes, you can. I do something similar at one of my sites, although with hrefinstead of id, but idworks too. A quick example:

是的你可以。我在我的一个网站上做了类似的事情,虽然用href而不是id,但也能id工作。一个简单的例子:

$('a[id]').click(function(e)
{
    // This will change the URL fragment. The change is reflected
    // on your browser's address bar as well
    window.location.hash = this.id;
    e.preventDefault();
});