通过 Ajax 加载的内容会中断按钮

Content loaded via Ajax breaks buttons

本文关键字:中断 按钮 Ajax 加载 通过      更新时间:2023-09-26

我有一个通过ajax加载的html页面,新加载的html内容具有以下html。当我先加载 html 然后初始化 javascript 时,它通常效果很好。

<a href="" class="ajax-button" data-url="/account/change-password">Change password</a>

我的js:

$('.ajax-button').on('click', OnLoadContent);
function OnLoadContent(e) {
    e.preventDefault();
    var pageurl = $(this).data('url');
    $.ajax({
        type: "GET",
        url: pageurl,
        success: function(data) {
            alert(data);
            $("#content-container").html(data);
            window.history.pushState({path:pageurl}, '', pageurl);
        },
        error: function(response) {
           alert("ERROR:" + response.responseText);
        }
    });
}

但是,由于正在加载的是新的 html 内容,我认为问题是通过 ajax 加载 html 内容时 javascript 已经存在,因此除非我再次单击,否则单击功能不起作用。我想知道如何解决这个问题?

将点击委托到更高的位置...

$('body').on('click', '.ajax-button', OnLoadContent);