Javascript 如何用另一个响应替换窗口的 URL 哈希?

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

How can I replace a window's URL hash with another response?

javascriptjqueryhashreplaceattr

提问by Barlas Apaydin

I am trying to change a hashed URL (document.location.hash) with the replace method, but it doesn't work.

我正在尝试使用替换方法更改散列 URL (document.location.hash),但它不起作用。

$(function(){
 var anchor = document.location.hash;
 //this returns me a string value like '#categories'

  $('span').click(function(){

     $(window).attr('url').replace(anchor,'#food');
     //try to change current url.hash '#categories'
     //with another string, I stucked here.
  });

});

I dont want to change/refresh page, I just want to replace URL without any responses.

我不想更改/刷新页面,我只想在没有任何响应的情况下替换 URL。

Note: I don't want to solve this with a href="#food" solution.

注意:我不想用 href="#food" 解决方案来解决这个问题。

回答by Fabrício Matté

Either use locationor window.locationinstead of document.locationas the latter is a non-standard.

要么使用location要么window.location代替,document.location因为后者是非标准的。

window.location.hash = '#food';

This will replace the URL's hash with the value you set for it.

这将使用您为其设置的值替换 URL 的哈希值。

Reference

参考

回答by arc

You may prefer the answer of this question.

你可能更喜欢这个问题的答案。

The difference being that with history.replaceState()you don't scroll to the anchor, only replace it in the navigation bar. It's supported by all major browsers, source.

不同之处在于history.replaceState()您不滚动到锚点,只在导航栏中替换它。所有主要浏览器都支持它,source

history.replaceState(undefined, undefined, "#hash_value")