【问题标题】:jQuery function history.replaceState() removes additional parameters from the URLjQuery 函数 history.replaceState() 从 URL 中删除附加参数
【发布时间】: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


    【解决方案1】:

    试试

    window.location.hash = '';
    

    而不是使用

    window.history.back();
    

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

    【讨论】:

    • 我会尝试.. 给我一分钟。但是,与此同时,我想提一下,当我尝试从底部注释代码块时,我发现它是 history.replaceState('', document.title, window.location.pathname),它正在删除散列和参数。因此,在我看来,这条线需要进行更改。请考虑看看。
    • 试过了,没用。正如我所说,这是导致问题的上述行。 window.history.back(); 应该不是问题,因为它应该从 http://localhost/gamearena/index.php?ref=shreyansh#sidebar-left 变为 http://localhost/gamearena/index.php?ref=shreyansh(在我看来)。
    • 我已经编辑了上面的问题,请注意。
    【解决方案2】:

    您的代码在设置哈希时并未更新历史记录,因此history.back() 会恢复到之前的 URL 状态。

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

    function addHash (hashString) {
      let myHash = '#' + hashString;
      location.hash = myHash;
      history.replaceState(null, null, myHash);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-10
      • 2014-10-25
      • 1970-01-01
      相关资源
      最近更新 更多