如何用另一个响应替换窗口的 URL 散列?

我试图用替换方法更改散列 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.
});


});

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

注意: 我不想用 href = “ # food”解决这个问题。

87619 次浏览

Either use location or window.location instead of document.location as the latter is a non-standard.

window.location.hash = '#food';

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

Reference

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(undefined, undefined, "#hash_value")