防止 history.replaceState 附加到 url

prevent history.replaceState appending to the url

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

它已被标记为 的副本,我认为这是一个错误,因为当我使用该代码时出现了同样的问题,并且它一直将索引附加到 url 中,如所述下面。

请看下面我的代码:

let index = 1;

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

我遇到的问题是 url 一直在附加数字,所以它正在做类似以下的事情:

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

有谁知道代码应该如何更新 url,如下所示:

还值得注意的是 url 是动态的,所以我无法对路径进行硬编码。我只想更新 url.

末尾的索引

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

let index = 1;

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

由于您要附加 /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.