追加Jquery后的Binding Click事件不起作用

Binding Click event after append Jquery not working

本文关键字:事件 不起作用 Click Binding Jquery 后的 追加      更新时间:2023-09-26

我有一个模式框,当点击表格中的加号图标时,它会弹出。页面加载后,表中会显示五行,单击加号会打开模式框。(效果很好)。

但是现在我们通过AJAX调用来更改表的内容。一旦TR被新的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>

处理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");

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

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

装订有什么问题?

当您向窗口附加一些内容时,只有运行jQuery,元素才存在。这意味着在定义单击事件时,单击事件所指向的元素不存在。所以你可以像这样使用身体作为选择器。

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

希望这能有所帮助!