Bar*_*din 54 javascript hash jquery replace attr
我试图用替换方法更改散列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.
});
});
Run Code Online (Sandbox Code Playgroud)
我不想更改/刷新页面,我只想更换URL而不做任何回复.
注意:我不想用href ="#food"解决方案来解决这个问题.
Fab*_*tté 105
使用location
或window.location
代替,document.location
因为后者是非标准的.
window.location.hash = '#food';
Run Code Online (Sandbox Code Playgroud)
这将使用您为其设置的值替换URL的哈希值.
arc*_*rcs 29
您可能更喜欢这个问题的答案.
不同之处在于history.replaceState()
您不会滚动到锚点,只能在导航栏中替换它.它是由所有主要浏览器,支持源.
history.replaceState(undefined, undefined, "#hash_value")
Run Code Online (Sandbox Code Playgroud)