[英]Remove hash from url
我是ajax-ifying在我的一个项目中的分页,因为我希望用户能够为当前页面添加书签,我通过哈希附加页码,说:
onclick="callPage(2); window.location.hash='p=2'; return false;"
并且它在hyperlink
上工作正常和一切,除了,当页码是1,我不想URL
为/products#p=1
,我只是想它是/products
我试过这些变化:
window.location.hash=''
工作,但网址现在像/products#
,我不是那里的哈希。 /products#p=3
因为我没有弄乱哈希。 <a href="#">
和他应该使用javascript:void(0)
代替。 (他们从未听说过Ajax吗?) 所以最后,我决定制作这个帖子,我在这里发现了几个类似的线程,但所有的答案与我的第二点非常相似。
所以我的一个大问题仍然是一个问题:如何从网址中挖出哈希,并可能离开宇宙? (仅限第一页!)
history.pushState("", document.title, window.location.pathname);
更新答案 :
实现这一目标的最佳方法是遵循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);
}
...但是这会为你刷新页面,这对你来到这里似乎有点小事。 咧嘴笑似乎是最好的选择。
var urlWithoutHash = document.location.href.replace(location.hash , "" );
完美地为我工作
$(window).on('hashchange', function(e){
window.history.pushState("", document.title, window.location.pathname);
// do something...
});
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.