Javascript 向 URL 添加片段而不导致重定向?

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

Add a fragment to the URL without causing a redirect?

javascriptjqueryhash

提问by Dee

Is there is a way how to add hash # to my URL without redirect?

有没有一种方法可以在不重定向的情况下将哈希 # 添加到我的 URL?

回答by alex

window.location.hash = 'something';

That is just plain JavaScript.

那只是普通的 JavaScript。

Your comment...

你的评论...

Hi, what I really need is to add only the hash... something like this: window.location.hash = '#';but in this way nothing is added.

嗨,我真正需要的是只添加哈希......像这样:window.location.hash = '#';但这样没有添加任何东西。

Try this...

尝试这个...

window.location = '#';

Also, don't forget about the window.location.replace()method.

另外,不要忘记window.location.replace()方法。

回答by Jess Telford

For straight HTML, with no JavaScript required:

对于直接 HTML,不需要 JavaScript:

<a href="#something">Add '#something' to URL</a>

Or, to take your question more literally, to just add '#' to the URL:

或者,从字面上理解您的问题,只需在 URL 中添加“#”:

<a href="#">Add '#' to URL</a>

回答by Daniel Lo Nigro

window.location.hash = 'whatever';