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
我试过这些变化:
window.location.hash=''工作,但网址现在像/products#,我不是那里的哈希./products#p=3因为我没有弄乱哈希.<a href="#">,他应该使用javascript:void(0).(他们从未听说过Ajax吗?)所以最后,我决定制作这个帖子,我在这里发现了几个类似的线程,但所有的答案与我的第二点非常相似.
所以我的一个大问题仍然是一个问题:如何从网址中挖出哈希,并可能离开宇宙?(仅限第一页!)
Hom*_*osa 92
history.pushState("", document.title, window.location.pathname);
Run Code Online (Sandbox Code Playgroud)
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)
...但是这会为你刷新页面,这对你来到这里似乎有点小事.咧嘴笑似乎是最好的选择.
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)