从 url 中删除哈希 [英] Remove hash from url

查看:45
本文介绍了从 url 中删除哈希的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am ajax-ifying the pagination in one of me projects and since I want the users to be able to bookmarks the current page, I am appending the page number via hash, say:

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

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

and thats on the hyperlink it works fine and everything, except, when the page number is 1, i dont want to URL to be /products#p=1, I just want it to be /products

我尝试了这些变体:

  1. window.location.hash='' 有效,但 url 现在类似于 /products#,我不太清楚那里的哈希值.
  2. 根本不使用 window.location.hash,但是当用户从第 1 页返回到第 1 页时,比如说第 3 页,他在第 1 页,但 url 仍然是 /products#p=3 因为我没有搞乱哈希.
  3. Google 对此的搜索使我进入了几分钟(大约 15 分钟)的愚蠢论坛,在那里问题被问到了正确的问题,但答案表明页面跳转是因为线程创建者在 href 中有一个哈希值,例如 <ahref="#"> 并且他应该使用 javascript:void(0) 代替.(他们从未听说过 Ajax 吗?)
  1. window.location.hash='' works but the url is now like /products# and I dont quite the hash there.
  2. not using window.location.hash at all, but when the user comes back to page 1 from, say page 3, he is in page one, but url is still /products#p=3 since I am not messing with the hash.
  3. Google search on this led me to several minutes (about 15) of silly forums where the question was asked right, but answers were suggesting that the page jumps because the thread creator had a hash in href like <a href="#"> and he should use javascript:void(0) instead. (had they never heard of Ajax?)

所以最后,我决定创建这个线程,我在这里找到了几个类似的线程,但所有的答案都与我的第二点非常相似.

So finally, I decided to make this thread, I found several similar threads here, but all the answers ls very similar to my second point.

所以我的大问题仍然是一个问题:如何将哈希值踢出 URL 并可能踢出宇宙?(仅限第一页!)

so my big question still remains a question: How to kick the hash out of the URL and possibly out of the universe? (only for the first page!)

推荐答案

更新答案:

实现这一目标的最佳方法是关注 Homero Barbosa下面的答案:

Best way to achieve this is to follow Homero Barbosa's answer below:

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

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

... or, if you want to maintain the search parameters:

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);
}

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

... but that refreshes the page for you which seems a trifle rude after just arriving there. Grin and bear it seems to be the best option.

这篇关于从 url 中删除哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆