javascript - jQuery 函数 history.replaceState() 从 URL 中删除附加参数
问题描述
我有以下 jQuery 代码,它在单击后退按钮时关闭引导模式。它工作正常。但是,当它关闭模式时,它应该#my-modal-id
从 URL 栏中删除它,它会这样做。但是,在这样做的同时,它还会从 URL 中删除额外的“必需”参数。例如:
当 URL 为: 时,它工作正常http://localhost/gamearena/index.php#my-modal-id
。在这里,它#my-modal-id
根据脚本从 URL 栏中删除。到目前为止,一切都很好。
但是,当 URL 具有其他参数(例如
http://localhost/gamearena/index.php?ref=shreyansh#sidebar-left
. ?ref=shreyansh
在这里,它甚至会随之移除。我该如何控制它,使它只删除之前自己设置的模态ID。
这是代码:
// Close model on clicking back button / swiping back
$('div.modal').on('show.bs.modal', function() {
var modal = this;
var hash = modal.id;
window.location.hash = hash;
window.onhashchange = function() {
if (!location.hash){
$(modal).modal('hide');
}
}
});
$('div.modal').on('hidden.bs.modal', function() {
var hash = this.id;
history.replaceState('', document.title, window.location.pathname);
});
// when close button clicked simulate back
$('div.modal button.close').on('click', function(){
window.history.back();
})
// when esc pressed when modal open simulate back
$('div.modal').keyup(function(e) {
if (e.keyCode == 27){
window.history.back();
}
});
编辑
稍微诊断后发现该行history.replaceState('', document.title, window.location.pathname);
负责改变这里的URL内容,即去掉hash等参数。此外,我注意到window.location.pathname
它只抓取 URL,index.php
而不是它之外的参数。因此,在我看来,该函数会将 URL 恢复为状态index.php
,而不是index.php?ref=shreyansh
因为它无法识别它。因此,我得出一个结论,如果window.location.pathname
替换为能够获取 URL 的函数,直到index.php?ref=shreyansh
(添加哈希部分之前的位置),问题将得到解决。因此,请专家对此有所了解。
解决方案
尝试
window.location.hash = '';
而不是使用
window.history.back();
如果要从 URL 中删除哈希。也会触发window.onhashchange
推荐阅读
- c - 我可以在 C17 中将“枚举”变量视为“int”吗?
- android - 颤振显示空白十字 (X) 图标
- python - 如何在tap支付方式中动态传递customer id来保存卡值
- amazon-web-services - SQS SendMessage 的高延迟
- sql - 如何使用 sql 表中的坐标作为 Weather URL API SSIS 脚本中的参数输入?
- swift - 聊天视图中的白色矩形空间
- android - 找不到builder-7.0.0-alpha09.jar
- javascript - 如何从 chrome 扩展程序创建隐身标签
- swagger - 如何为 url 构建路径和响应对象
- python - 使用 Python 接收外国 UDP 广播