在追加Jquery不工作后绑定Click事件

时间:2015-03-28 22:54:48

标签: javascript jquery html ajax

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

但现在我们正在通过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>

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

绑定有什么问题?

1 个答案:

答案 0 :(得分:3)

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

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

希望这有帮助!