简体   繁体   English

附加Jquery后无法绑定Click事件

[英]Binding Click event after append Jquery not working

I've got a modal box that pops up popups when the plus icon is clicked in a table. 我有一个模式框,当在表中单击加号图标时,该弹出框会弹出弹出窗口。 After the page is loaded five rows are displayed in the table and clicking the plus sign opens the modal box. 加载页面后,表中将显示五行,单击加号将打开模式框。 (Works perfectly). (完美运行)。

But now we are changing the content of the table by an AJAX call. 但是现在我们通过AJAX调用来更改表的内容。 Once the TR's are replaced by new ones, the plus signs aren't working any more. 一旦TR被新的替换,加号就不再起作用。

I'm aware of the fact that the event-handler 我知道事件处理程序的事实

Table: 表:

<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>

The Jquery Part that handles the AJAX (and works, replaced the table according to the JSON respons). 处理AJAX的Jquery Part(并且工作,根据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");

Now the event Handler, works after document is ready, but stops working once the AJAX call has replaced the data. 现在,事件处理程序在文档准备就绪后开始工作,但是一旦AJAX调用替换了数据后就停止工作。

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

What's wrong with the binding? 绑定有什么问题?

When you append something to the window, the element doesn't exist until you run the jQuery. 当您将某些内容添加到窗口时,该元素在运行jQuery之前不存在。 That means the element the click event points to doesn't exist when the click event is defined. 这意味着在定义click事件时,click事件指向的元素不存在。 So you can use the body as a selector like this. 因此,您可以像这样将主体用作选择器。

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

Hope this helped! 希望这对您有所帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM