【发布时间】:2021-12-14 13:43:03
【问题描述】:
我正在使用带有 jquery 的 php 和 mysql 来显示我的数据。最初的
我的on 点击事件正在处理tbody 的时间。
但是当我用 ajax 调用附加 tbody 时,它不起作用。我正在使用带有.on的事件委托
我的 html 表: 我正在使用简单的 html 表来显示我的数据和任何 TD 添加 ajax 以追加数据的 onclick。
<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){} ); -
@Stender 我怀疑这会解决问题,因为 OP 表示它已经在初始加载时工作,表明 #NewsTable 始终存在。
-
阿米特,你没有向我们展示 ajax.php 的代码我不认为。它返回什么?
-
@ADyson 很好,它与接受的答案相同,所以它可能已经解决了这个问题;)
标签: php jquery ajax append event-delegation