我正在使用window.history.replaceState
并遇到一些问题,因为它一直附加到网址中。
它被标记为this question的重复,我认为这是一个错误,因为当我使用该代码时,会发生相同的问题,并且它会继续将索引附加到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是动态的,因此我无法对路径进行硬编码。我只想更新网址末尾的索引。
答案 0 :(得分:2)
由于要附加/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>
答案 1 :(得分:0)
您应该在window.location.origin中执行此操作,然后开始附加路径名,因此答案可能是
let index = 1;
function incrementIndexAndUpdateUrl() {
index++;
window.history.replaceState('Object', 'Title', `${window.location.origin}/question/ask/${index}`);
}