从url中删除哈希

iam*_*ous 52 javascript ajax fragment-identifier

我是ajax-ifying在我的一个项目中的分页,因为我希望用户能够为当前页面添加书签,我通过哈希附加页码,说:

onclick="callPage(2); window.location.hash='p=2'; return false;"
Run Code Online (Sandbox Code Playgroud)

并且hyperlink它在它上面工作正常和一切,除了,当页码是1,我不想URL成为/products#p=1,我只是希望它是/products

我试过这些变化:

  1. window.location.hash=''工作,但网址现在像/products#,我不是那里的哈希.
  2. 根本没有使用window.location.hash,但当用户从第3页回到第1页时,他在第一页,但是url仍然是/products#p=3因为我没有弄乱哈希.
  3. 谷歌搜索这导致我几分钟(约15)愚蠢的论坛,问题被正确,但答案是建议页面跳跃,因为线程创建者在href中有一个哈希<a href="#">,他应该使用javascript:void(0).(他们从未听说过Ajax吗?)

所以最后,我决定制作这个帖子,我在这里发现了几个类似的线程,但所有的答案与我的第二点非常相似.

所以我的一个大问题仍然是一个问题:如何从网址中挖出哈希,并可能离开宇宙?(仅限第一页!)

Hom*_*osa 92

history.pushState("", document.title, window.location.pathname);
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,正是我需要的东西(虽然被授予,但我不介意删除查询参数(但是,可以通过简单地添加查询字符串来维护,例如`history.pushState('',document.title,window) .location.pathname + window.location.search);`)) (9认同)
  • 如果你担心@enyo问题,history.replaceState(...)可能会更合适 (9认同)
  • 这也创造了历史中的一个条目(显然).因此,当用户单击后退按钮时,她将在同一页面上. (4认同)
  • 如果你投票我的回复,我将不胜感激:) (3认同)
  • 适用于新浏览器,但IE9及更低版本不支持它.就像指出这一点. (2认同)

wom*_*ton 54

更新答案:

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

history.pushState("", document.title, window.location.pathname);
Run Code Online (Sandbox Code Playgroud)

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

history.pushState("", document.title, window.location.pathname + window.location.search);
Run Code Online (Sandbox Code Playgroud)

原始答案,不要使用此,badwrongfun:

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

if (index > 0) {
  window.location = loc.substring(0, index);
}
Run Code Online (Sandbox Code Playgroud)

...但是这会为你刷新页面,这对你来到这里似乎有点小事.咧嘴笑似乎是最好的选择.

  • history.pushState("",document.title,window.location.pathname); 还将删除php查询字符串,即"?key = hello".如何在不删除查询字符串的情况下删除哈希值? (2认同)

Dev*_*dev 5

var urlWithoutHash = document.location.href.replace(location.hash , "" );
Run Code Online (Sandbox Code Playgroud)


小智 5

完美地为我工作

$(window).on('hashchange', function(e){
  window.history.pushState("", document.title, window.location.pathname);  
 // do something...
});
Run Code Online (Sandbox Code Playgroud)