如何使 pushState/onpopstate 和 jQuery 事件(例如点击)正常工作?

How to make pushState/onpopstate and jQuery events (e.g. on click) work nicely?

我能够成功地使用 pushState 和 onpopstate 来使用 AJAX 启用页面上的 back/forward 按钮。

AJAX 功能的一个方面是在单击 link 时自动刷新下拉列表。这是我的代码此功能。

<a class="type" href="#Chr(35)#" data-type="B">B</a>
| <a class="type" href="#Chr(35)#" data-type="H">H</a>

window.addEventListener("popstate", function(event) {
    if (event.state) {
        document.getElementById("content").innerHTML = event.state.html;
    }
});

$(".type").on("click", function (event) {
    console.log("im here");

    event.preventDefault();

    getCourses({ type:$(this).data("type") });

    try {
        window.history.pushState({ "html": document.getElementById("content").innerHTML }, "", globalvars.baseurl+"/my/main?type="+$(this).data("type"));
    } catch(exception) {
    }
});

问题发生在我按下后退按钮并呈现内容部分的已保存副本时。当我尝试单击上面的 links 时,它不会触发(即 "im here" 现在不会显示在我的控制台中,在我按下后退按钮之前它曾经工作)

似乎解决方案是在我的事件侦听器中复制 link 的点击功能,特别是在 "if (event.state)...".[=15= 之后]

window.addEventListener("popstate", function(event) {
    if (event.state) {
        document.getElementById("content").innerHTML = event.state.html;

        $(".type").on("click", function (event) { console.log("im here") });
    }
});

$(".type").on("click", function (event) {
    console.log("im here");

    event.preventDefault();

    getCourses({ type:$(this).data("type") });

    try {
        window.history.pushState({ "html": document.getElementById("content").innerHTML }, "", globalvars.baseurl+"/my/main?type="+$(this).data("type"));
    } catch(exception) {
    }
});

这意味着我需要在 2 个地方编写相同的代码。我能想到的唯一选择是删除点击功能的内容并将其放入自定义功能中。

window.addEventListener("popstate", function(event) {
    if (event.state) {
        document.getElementById("content").innerHTML = event.state.html;

        $(".type").on("click", function (event) { test($(this).data("type")); });
    }
});

$(".type").on("click", function (event) { test($(this).data("type")); });

function test(type) {
    console.log("im here");

    event.preventDefault();

    getCourses({ type:type });

    try {
        window.history.pushState({ "html": document.getElementById("content").innerHTML }, "", globalvars.baseurl+"/my/main?type="+type);
    } catch(exception) {
    }
}

还有其他方法吗?

非常感谢

两种方法...一种是将内部函数存储在变量中:

var typeClickHandler = function (event) {
  test($(this).data("type"));
};

然后在需要时在两个地方使用该处理程序:

$(".type").on("click", typeClickHandler);

其他方法是使用事件委托...这意味着侦听器在文档中或您要侦听的此元素的某个父级上:

$(document).on('click', '.type', function (event) {
  // note that we use event.target instead of this here
  test($(event.target).data("type"));
});

当然,您可以结合这两种解决方案:

var typeClickHandler = function (event) {
  test($(event.target).data("type"));
};
$(document).on('click', '.type', typeClickHandler);