【发布时间】:2019-07-04 04:42:57
【问题描述】:
我有一个模态框的问题,它在打开时会在当前 url 中添加一个哈希(可能有其他哈希)
01
这段代码对我来说很好,但是当哈希被删除时会留下这个 "#"
window.location.hash = location.hash.replace(/#About/, '');
示例 当模式打开时: www.mywebsite.com/#products#About
当模态关闭时: www.mywebsite.com/#products#
我想得到什么: www.mywebsite.com/#products
02
也可以试试这个,它可以正常工作,但消除了所有以前的哈希
history.pushState("", document.title, window.location.pathname);
或
history.pushState("", document.title, window.location.pathname + window.location.search);
结果:
当模式打开时: www.mywebsite.com/#products#About
当模态关闭时: www.mywebsite.com(我不想删除以前的哈希)
这是我的代码:
$(".barMenuFooter a.buttonShowDetail").on('click', function(){
$(this).toggleClass('active');
if ($(this).hasClass("active")) {
window.location.hash = location.hash + "#About";
openAbout();
}
else {
window.location.hash = location.hash.replace(/#About/, '');
closeAbout();
}
});
我只想完全删除最后添加的哈希(不带#)而不重新加载页面。
【问题讨论】:
-
试试
window.location.hash = window.location.hash.split('#').slice(0,-1).join('#')。看看有没有帮助
标签: javascript jquery url hash window.location