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

时间:2012-05-16 05:18:52

标签: javascript jquery

我试图在一些进程之后在外部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;

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

8 个答案:

答案 0 :(得分:136)

window.location.href += "#mypara";
location.reload();

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

经过测试,有效。


ps:如果网址中已存在哈希,您可能希望通过location.hash而不是.href直接更改。

答案 1 :(得分:30)

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

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

答案 2 :(得分:22)

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

  1. location.reload()location.reload(true)在浏览器上与F5类似。如果先前已加载,则会将所有表单数据发布回服务器。
  2. 在浏览器识别出URL更改之前,
  3. location.href不会刷新页面。散列更改(#paramname)不符合URL更改的条件,因此只是这样做 location.href+="#paramname"无效。
  4. 因此,location.href+="?anything#paramname"应该将页面重新加载为新请求,因为?anything更改了网址。

答案 3 :(得分:0)

var loc = location.hash;
location.hash = " ";
location.hash = loc;

答案 4 :(得分:-1)

试试这个

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

答案 5 :(得分:-1)

这对我有用:

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

答案 6 :(得分:-1)

这对我有用

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

答案 7 :(得分:-1)

这项工作对我来说

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