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

时间:2021-06-16 21:08:52

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”解决方案来解决这个问题。

2 个解决方案

#1


84  

Either use location or window.location instead of document.location as 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

参考

#2


14  

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()不同的是,您不会滚动到锚点,只能在导航栏中替换它。它得到了所有主流浏览器的支持。

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

#1


84  

Either use location or window.location instead of document.location as 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

参考

#2


14  

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()不同的是,您不会滚动到锚点,只能在导航栏中替换它。它得到了所有主流浏览器的支持。

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