61

我在我的一个项目中对分页进行 ajax 化,并且由于我希望用户能够为当前页面添加书签,因此我通过哈希附加页码,例如:

onclick="callPage(2); window.location.hash='p=2'; return false;"

就是这样,hyperlink它工作正常,一切正常,除了页码为 1 时,我不想URL成为/products#p=1,我只是希望它成为/products

我尝试了这些变化:

  1. window.location.hash=''有效,但现在的 url 是这样的/products#,我不太喜欢那里的哈希值。
  2. 根本不使用 window.location.hash,但是当用户从第 3 页回到第 1 页时,他在第 1 页,但 url 仍然存在,/products#p=3因为我没有弄乱哈希。
  3. 谷歌搜索这让我进入了几分钟(大约 15 分钟)的愚蠢论坛,在那里问题被正确提出,但答案表明页面跳转,因为线程创建者在 href 中具有哈希<a href="#">,他应该使用javascript:void(0)。(他们从未听说过阿贾克斯吗?)

所以最后,我决定做这个帖子,我在这里找到了几个类似的帖子,但所有的答案都与我的第二点非常相似。

所以我的大问题仍然是一个问题:如何将散列踢出 URL 并可能踢出宇宙?(仅适用于第一页!)

4

5 回答 5

94
history.pushState("", document.title, window.location.pathname);
于 2012-03-10T02:10:39.017 回答
68

更新答案

实现这一目标的最佳方法是遵循以下Homero Barbosa回答

history.pushState("", document.title, window.location.pathname);

...或者,如果您想维护搜索参数:

history.pushState("", document.title, window.location.pathname + window.location.search);

原始答案,不要使用这个,badwrongfun

var loc = window.location.href,
    index = loc.indexOf('#');

if (index > 0) {
  window.location = loc.substring(0, index);
}

...但这会为您刷新页面,这在刚到达那里后似乎有点粗鲁。咧嘴一笑,这似乎是最好的选择。

于 2010-12-22T11:35:16.407 回答
7

完美地为我工作

$(window).on('hashchange', function(e){
  window.history.pushState("", document.title, window.location.pathname);  
 // do something...
});
于 2016-06-16T08:05:17.650 回答
5
var urlWithoutHash = document.location.href.replace(location.hash , "" );
于 2013-09-27T06:00:49.797 回答
4
function removeHash () { 
    var scrollV, scrollH, loc = window.location;
    if ("pushState" in history)
        history.pushState("", document.title, loc.pathname + loc.search);
    else {
        // Prevent scrolling by storing the page's current scroll offset
        scrollV = document.body.scrollTop;
        scrollH = document.body.scrollLeft;

        loc.hash = "";

        // Restore the scroll offset, should be flicker free
        document.body.scrollTop = scrollV;
        document.body.scrollLeft = scrollH;
    }
}
于 2015-10-28T05:59:53.033 回答