使用pushState轻微异常 - 更改URL" state"点击

时间:2017-11-07 22:28:46

标签: javascript jquery

所以我编写了以下脚本,其中包含一个处理pushState调用的函数和一些调用onClick函数的jQuery:

function pushUrlState(id, url) {
    if (typeof (history.pushState) != "undefined") {
        var obj = { Id: id, Url: url };
        history.pushState(obj, obj.Id, obj.Url);
    } else {
        alert("This browser does not support HTML5.");
    }
}
$(function () {
    $("#id1").click(function () {
        pushUrlState('Id1', '2017/15/05/my-birthday-is-today');
    });
    $("#id2").click(function () {
        pushUrlState('Id2', '2017/14/05/my-birthday-is-tomorrow');
    });
    $("#id3").click(function () {
        pushUrlState('Id3', '2017/16/05/my-birthday-was-yesterday');
    });
});

工作非常好,但经过多次点击各种元素后,我最终得到以下内容:

http://127.0.0.1:3000/2017/15/05/2017/14/05/2017/16/05/2017/14/05/2017/14/05/2017/14/05/2017/14/05/2017/14/05/2017/14/05/2017/14/05/2017/14/05/2017/14/05/2017/14/05/2017/14/05/2017/14/05/my-birthday-is-tomorrow

是否有一些我可以调用的功能可以将URL杀回域名?

1 个答案:

答案 0 :(得分:0)

您传入相对网址(您的网址不以/开头)。

https://developer.mozilla.org/en-US/docs/Web/API/History_API#The_pushState()_method

  

URL - 此历史记录条目的URL由此参数指定。注意   调用后浏览器不会尝试加载此URL   pushState(),但它可能会稍后尝试加载URL   用户重启浏览器后。 不需要新网址   绝对;如果它是相对的,则相对于当前URL进行解析。   新网址必须与当前网址的来源相同;除此以外,   pushState()将抛出异常。此参数是可选的;如果它   未指定,它被设置为文档的当前URL。

在控制台中尝试以下两个代码段并查看差异:

这与您的代码(相对网址)

相似
[1,2,3,4,5,6,7,8,9]
.forEach(
  num =>
    //relative url (does not start with /
    history.pushState({}, `page ${num}`, `hello${num}/world${num}.html`)
)

这表现得像你喜欢它的行为:

[1,2,3,4,5,6,7,8,9]
.forEach(
  num =>
    //absolute url start with /
    history.pushState({}, `page ${num}`, `/hello${num}/world${num}.html`)
)