在 ajax 调用中追加 tbody 后点击事件不起作用?

on click event not working after append tbody in ajax call?

我正在使用 php 和 mysql 以及 jquery 来显示我的数据。最初的 我的 on 单击事件在 tbody.

上运行的时间

但是当我用 ajax 调用附加 tbody 时它不起作用。我正在使用 .on

的事件委托

我的 html table : 我正在使用简单的 html table 来显示我的数据,并点击任何添加 ajax 的 TD 来附加数据。

 <table id="NewsTable" class="display" width="100%" cellspacing="0">
            <thead>
                <tr> 
                    <th class="th-sm">Headline</th>
                    <th class="th-sm">Main Category</th>
                </tr>
            </thead>
            <tbody>
                foreach($data as $val){ // php data foreach loop.(ignore)
                      <tr class='".$x++."className'> // using dynamic class name and id everywhere.
                  <td  class='".$x++."className1'><?php echo $val['data1']?></td>
                  <td  class='".$x++."className2'><?php echo $val['data2']?></td>
                </tr>
                }
            </tbody>
        <table>

我的 ajax 电话:

$('#NewsTable').on('click','td', function(e) {
            e.preventDefault();
             $.ajax({
                type: "POST",
                url: 'ajax.php',
                data: 'data',
                beforeSend: function() {
                    $('#loader').show();
                },
                success: function(response) {
                    $('#NewsTable tbody').empty();
                    $('#NewsTable tbody').append(response); // data is coming properly here. but Now on click event not working.
                },
                error: function(xhr, status, error) {
                    console.log(error);
                },
            });
});
   

尝试像这样更改选择器以定位文档:

$(document).on('click','#NewsTable td', function(e) {
            e.preventDefault();
             $.ajax({
                type: "POST",
                url: 'ajax.php',
                data: 'data',
                beforeSend: function() {
                    $('#loader').show();
                },
                success: function(response) {
                    $('#NewsTable tbody').empty();
                    $('#NewsTable tbody').append(response); // data is coming properly here. but Now on click event not working.
                },
                error: function(xhr, status, error) {
                    console.log(error);
                },
            });
});

此代码$('#NewsTable tbody').empty();正在删除附加了监听器的元素,因此新元素在附加后没有点击监听器。