从 url 中删除哈希

IT技术 javascript ajax fragment-identifier
2021-02-05 15:26:00

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

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

就是这样,hyperlink它工作正常,一切正常,除了当页码为 1 时,我不想URL成为/products#p=1,我只想成为/products

我尝试了这些变化:

  1. window.location.hash=''有效,但 url 现在是这样的/products#,我不太清楚那里的哈希值。
  2. 根本不使用 window.location.hash,但是当用户从第 1 页返回到第 1 页时,比如说第 3 页,他在第 1 页,但 url 仍然存在,/products#p=3因为我没有弄乱哈希值。
  3. 对此的谷歌搜索让我进入了几分钟(大约 15 分钟)的愚蠢论坛,在那里问题被问到了正确的问题,但答案表明页面跳转,因为线程创建者在 href 中具有哈希值<a href="#">,他应该使用它javascript:void(0)来代替。(他们从没听说过 Ajax 吗?)

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

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

5个回答
history.pushState("", document.title, window.location.pathname);
适用于新浏览器,但 IE9 及以下版本不支持。只是想指出这一点。
2021-03-20 15:26:00
如果您担心 @enyo 问题, history.replaceState( ... ) 可能更合适
2021-03-20 15:26:00
只是快速尝试一下,它也删除了查询参数......不可取!
2021-03-24 15:26:00
这也会在历史记录中创建一个条目(显然)。因此,当用户单击后退按钮时,她将在同一页面上。
2021-04-09 15:26:00
谢谢,正是我所需要的(虽然被授予,但我不介意删除查询参数(但是,只需添加查询字符串即可毫无问题地进行维护,例如history.pushState('', document.title, window.location.pathname+window.location.search);))
2021-04-13 15:26:00

更新答案

实现这一目标的最佳方法是遵循以下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);
}

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

history.pushState("", document.title, window.location.pathname); 还将删除 php 查询字符串,即“?key=hello”。我们如何在不删除查询字符串的情况下只删除哈希?
2021-03-20 15:26:00
我得到了未定义的名称“历史”
2021-03-26 15:26:00
下面是更好的答案!!
2021-03-29 15:26:00
你也可以妥协并接受一些/products#First/products#p=1:)更优雅的东西
2021-04-06 15:26:00
这对我有用,您也可以再次保存字符串而不是更改页面: var hashIndex = userUrl.indexOf('#'); if (hashIndex > 0) { userUrl = userUrl.substring(0, hashIndex); }
2021-04-12 15:26:00

完美地为我工作

$(window).on('hashchange', function(e){
  window.history.pushState("", document.title, window.location.pathname);  
 // do something...
});
到目前为止,最好和最简单的答案。
2021-04-11 15:26:00
var urlWithoutHash = document.location.href.replace(location.hash , "" );
这有问题,比如哈希是否是一个短词。
2021-03-27 15:26:00
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;
    }
}
请在您的答案中添加解释。
2021-03-17 15:26:00
这是从这个答案中无耻地复制的
2021-04-05 15:26:00