[英]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.