首页 > 解决方案 > 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(添加哈希部分之前的位置),问题将得到解决。因此,请专家对此有所了解。

标签: javascripthtmljquerytwitter-bootstrapbootstrap-modal

解决方案


尝试

window.location.hash = '';

而不是使用

window.history.back();

如果要从 URL 中删除哈希。也会触发window.onhashchange


推荐阅读