【问题标题】:prevent history.replaceState appending to the url防止 history.replaceState 附加到 url
【发布时间】:2018-09-17 14:24:17
【问题描述】:

我正在使用window.history.replaceState 并遇到一些问题,因为它一直附加到网址。

它已被标记为 this question 的副本,我认为这是一个错误,因为当我使用该代码时,同样的问题正在发生,并且它不断将索引附加到 url,如下所述。

请看我下面的代码:

let index = 1;

function incrementIndexAndUpdateUrl() {
   index++;
   window.history.replaceState('Object', 'Title', `${window.location.href }/${index}`);
}

我遇到的问题是网址不断附加数字,因此它正在执行以下操作:

https://slackoverflowz.com/questions/ask/2/3/4

有谁知道更新 url 的代码应该是什么样子,如下所示:

还值得注意的是 url 是动态的,所以我不能硬编码路径。我只想更新网址末尾的索引。

【问题讨论】:

  • 您是否尝试过删除最后的数字,然后添加索引?
  • @LucaKiebel 你是什么意思?
  • const index 和 index++? window.location.href 也将包含您刚刚附加的数字
  • 你应该从window.location.origin开始添加pathname
  • @George 对不起,我只是在这里写了代码,它实际上是在一个。反应组件,const 没有问题。不过你是对的,这就是问题

标签: javascript html5-history


【解决方案1】:

由于您附加了/something,因此您实际上是在更改路径名。 所以最简单的方法是在更改之前存储原始文件:

let index = 1;
const path = location.pathname;

btn.onclick = incrementIndexAndUpdateUrl;

function incrementIndexAndUpdateUrl() {
   index++;
   window.history.replaceState('Object', 'Title', `${path}/${index}`);
   console.log(location.href);
}
<button id="btn">increment</button>

And as a fiddle for Chrome.

【讨论】:

    【解决方案2】:

    你应该从 window.location.origin 开始并开始附加路径名,所以你的答案可能是

    let index = 1;
    
    function incrementIndexAndUpdateUrl() {
       index++;
      window.history.replaceState('Object', 'Title', `${window.location.origin}/question/ask/${index}`);
    }
    

    【讨论】:

    • 对不起@mohit 网址是动态的
    猜你喜欢
    • 2020-09-13
    • 1970-01-01
    • 2016-04-30
    • 2014-02-19
    • 2011-04-24
    • 2020-08-10
    • 1970-01-01
    • 2023-02-07
    • 1970-01-01
    相关资源
    最近更新 更多