【发布时间】:2020-09-13 18:56:00
【问题描述】:
我有以下 jQuery 代码,它在单击后退按钮时关闭引导模式。它工作正常。但是,当它关闭模式时,它应该从 URL 栏中删除 #my-modal-id,它会这样做。但是,在这样做的同时,它还会从 URL 中删除额外的“必需”参数。例如:
当 URL 为:http://localhost/gamearena/index.php#my-modal-id 时,它可以正常工作。在这里,它根据脚本从 URL 栏中删除 #my-modal-id。到目前为止,一切都很好。
但是,当 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 只抓取到index.php 的URL,而不是它之外的参数。因此,在我看来,该函数将 URL 恢复为状态 index.php 而不是 index.php?ref=shreyansh,因为它无法识别它。因此,我得出的结论是,如果将window.location.pathname 替换为能够获取URL 直到index.php?ref=shreyansh(添加哈希部分之前的位置)的函数,则问题将得到解决。因此,请专家对此有所了解。
【问题讨论】:
标签: javascript html jquery twitter-bootstrap bootstrap-modal