![](/img/trans.png)
[英]click event not call event after load `<a href=“#”>btn</a>` with `ajax`
[英]on click event not working after append tbody in ajax call?
我正在使用帶有 jquery 的 php 和 mysql 來顯示我的數據。 我on
點擊事件的初始時間是在tbody
on
工作。
但是當我用 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) {
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();
正在刪除附加了偵聽器的元素,因此新元素在附加后沒有點擊偵聽器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.