附加 Jquery 后绑定 Click 事件不起作用

Pet*_*Fox 1 html javascript ajax jquery

我有一个模式框,当单击表格中的加号图标时会弹出弹出窗口。页面加载后,表格中会显示五行,单击加号可打开模式框。(完美运行)。

但是现在我们正在通过 AJAX 调用更改表的内容。一旦 TR 被新的替换,加号就不再起作用了。

我知道事件处理程序

桌子:

<table class="table table-hover" id="carsTable">
    <thead>
    <tr>
        <th>Car Title</th>
        <th>Actions</th>
    </tr>
    </thead>
    <tbody>
        <tr id="car-1836">
            <td>ferrari f50</td>
            <td><a href="#" class="black-modal-80" id="5269327"><i class="glyph-icon icon-plus-circle">+</i></a></td>
        </tr>
    </tbody>
    <tfoot>
    <tr>
        <th>Product Title</th>
        <th>Actions</th>
    </tr>
    </tfoot>
</table>
Run Code Online (Sandbox Code Playgroud)

处理 AJAX 的 Jquery 部分(并且有效,根据 JSON 响应替换了表)。

$.post("../../../scripts/getCars.php", {s: carSearch}, function (data) {
    $("tr[id='carLoader']").remove();

    $.each(data, function (index) {
        if ($('#selectedCar-' + data[index].externalProductId + '').length == 0) {
            $('#carsTable')
                    .append('<tr id="car-'+ data[index].id+'"><td>' + data[index].title + '</td><td><a href="#" class="black-modal-80" id="' + data[index].externalProductId + '"><i class="glyph-icon icon-plus-circle"></i></a></td></tr>');
        }
    });

}, "json");
Run Code Online (Sandbox Code Playgroud)

现在事件处理程序在文档准备好后工作,但一旦 AJAX 调用替换了数据就停止工作。

$('#carsTable').on('click', '.black-modal-80', function () {
    console.log('Click detected; modal will be displayed');
});
Run Code Online (Sandbox Code Playgroud)

绑定有什么问题?

Max*_*lin 7

当您向窗口追加内容时,该元素在您运行 jQuery 之前不存在。这意味着在定义单击事件时,单击事件指向的元素不存在。所以你可以像这样使用 body 作为选择器。

$('body').on('click', '.black-modal-80', function () {
    console.log('Click detected; modal will be displayed');
});
Run Code Online (Sandbox Code Playgroud)

希望这有帮助!