Javascript使用哈希值重新加载页面

Jon*_*s T 71 javascript jquery

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

window.location.href = window.location.href
Run Code Online (Sandbox Code Playgroud)

它完美地重新加载页面,但我想在重新加载后滚动到特定位置.所以,我把它放在页面上.

<a name="uploadImgSection"></a>
Run Code Online (Sandbox Code Playgroud)

并将javascript更改为

window.location.href = window.location.href + "#mypara";
Run Code Online (Sandbox Code Playgroud)

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

window.location.hash = "#uploadImgSection";
window.location.href = window.location.href;
Run Code Online (Sandbox Code Playgroud)

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

Der*_*會功夫 143

window.location.href += "#mypara";
location.reload();
Run Code Online (Sandbox Code Playgroud)

首先添加哈希,然后重新加载页面.哈希将保留在那里,并重新加载页面.

经过测试,有效.


ps:如果URL中已存在哈希,您可能希望直接更改它location.hash而不是.href.

  • 你是天才德里克.有用.谢啦. (3认同)

ug_*_*ug_ 32

我想更新这个问题,因为我发现window.location.href += "#mypara"即使它存在,使用将继续将参数附加到网址.我发现更好的方法是使用

window.location.hash = "#mypara"
location.reload();
Run Code Online (Sandbox Code Playgroud)


小智 22

这真是一个老帖子,我仍然会尝试用正确的答案组合来回答.

  1. location.reload()location.reload(true)浏览器上的F5类似.如果之前已加载,则会将所有表单数据发布回服务器.
  2. location.href在浏览器识别出URL更改之前,不会刷新页面.散列更改(#paramname)不符合URL更改的条件,因此只是执行操作 location.href+="#paramname"不起作用.

因此,location.href+="?anything#paramname"应该将页面重新加载为新请求,因为?anythingURL中的更改.

  • 另一个:location.href + ='&rand ='+ Math.rand()+'#myhash'; (4认同)