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

佐手、 提交于 2019-12-03 10:24:49

问题


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

$(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.

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


回答1:


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




回答2:


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")


来源:https://stackoverflow.com/questions/11588482/how-can-i-replace-a-windows-url-hash-with-another-response

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!