Javascript 使用 hash 值重新加载页面

在一些进程之后,我试图在外部 javascript 文件中用这个语句刷新页面。

window.location.href = window.location.href

它完美的重新加载页面,但我想滚动到特定的位置后,重新加载。 所以,我把这个写在纸上。

<a name="uploadImgSection"></a>

并将 javascript 更改为

window.location.href = window.location.href + "#mypara";

这段代码也不会重新加载/刷新页面

window.location.hash = "#uploadImgSection";
window.location.href = window.location.href;

当我这样做时,它根本不会重新加载页面。有什么办法可以重新加载页面与滚动条的位置?

99809 次浏览

Try this

           var urlString=window.location.href;
var url=urlString.split("#")[0];
window.location.href = url + "#mypara";
window.location.href += "#mypara";
location.reload();

First add the hash, then reload the page. The hash will remain there, and the page gets reloaded.

Tested, works.


ps: If a hash already exist in the URL, you may want to directly change it via location.hash instead of .href.

This is really an old post, I would still try and answer with right combination of answers.

  1. location.reload() and location.reload(true) works like F5 on browser. This will post all the form data back to the server if previously load had done it.
  2. location.href will not refresh the page until there is a URL change recognized by the browser. change in hash (#paramname) doesn't qualify for URL change and hence just doing location.href+="#paramname" will not work.

So, location.href+="?anything#paramname" should reload the page as a new request as ?anything is change in the URL.

I wanted to update this question because I found that using window.location.href += "#mypara" will keep appending the parameter to the url even if it exists. I have found the better way is to use

window.location.hash = "#mypara"
location.reload();

This worked for me:

var tabValue = document.URL;
window.location = tabValue.substring(0, tabValue.lastIndexOf("#"));
window.location.hash = "#tabs-3"; //Whatever is your hash value
location.reload();
var loc = location.hash;
location.hash = " ";
location.hash = loc;

This worked for me

$('body').on('click', '.className', function () {
var data = $(this).attr('href');
alert(data);
window.location.reload();
});

This work for me

window.location.href = baseUrl + "#/m/team";
location.reload();