jQuery函数history.replaceState()从URL中删除其他参数

问题描述 投票:1回答:2

我有以下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的内容,即删除哈希和其他参数。此外,我注意到window.location.pathname仅捕获直到index.php的URL,而不捕获超出其的参数。因此,我认为该函数将URL恢复为状态index.php而不是index.php?ref=shreyansh,因为它无法识别它。因此,我得出的结论是,如果将window.location.pathname替换为能够提取高达index.php?ref=shreyansh的URL(添加哈希部分之前的位置)的功能,则可以解决此问题。因此,请专家对此进行一些说明。

javascript html jquery twitter-bootstrap bootstrap-modal
2个回答
0
投票

尝试

window.location.hash = '';

代替使用

window.history.back();

如果要从URL中删除哈希。它还将触发window.onhashchange


0
投票

您的代码在设置哈希值时不会更新历史记录,因此history.back()会恢复为较早的URL状态。

这将更新哈希和历史记录:

function addHash (hashString) {
  let myHash = '#' + hashString;
  location.hash = myHash;
  history.replaceState(null, null, myHash);
}
© www.soinside.com 2019 - 2024. All rights reserved.