对于新的动态创建的元素,单击事件不持久

Click event does not persist for new dynamically created elements

本文关键字:单击 事件 不持久 创建 于新 动态 元素      更新时间:2023-09-26

我有一些附加到类的click事件的代码:

$(".filter-link").click(function (e) {
    $("#filter").dialog("option", "position",
                    { my: "left top", at: "left bottom", of: e });
    $("#filter").dialog("open");
});

我所使用的元素通常是动态重新创建的:

function addTopLinks() {
    $('#calendar .fc-view thead th.fc-resourceName')
        .removeClass('top-calendar-cell');
    $('#calendar .fc-view thead th.fc-resourceName')
        .addClass('top-calendar-cell');
    $('#calendar .fc-view thead th.fc-resourceName')
        .html('<a class="filter-link" href="#">Filter Resources</a>');
};

是否有任何方法可以让单击持续存在,或者每次重新创建元素时都会强制重新分配单击?

谢谢

使用.on():

$(document).on("click", ".filter-link", function (e) {
     $("#filter").dialog("option", "position",
            { my: "left top", at: "left bottom", of: e });
     $("#filter").dialog("open");
});