我正在使用帶有 jquery 的 php 和 mysql 來顯示我的資料。我的on點擊事件處理的初始時間tbody。
但是當我用 ajax 呼叫附加 tbody 時,它不起作用。我正在使用事件委托.on
我的 html 表:我使用簡單的 html 表來顯示我的資料,并單擊任何 TD 添加 ajax 來附加資料。
<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);
},
});
});
uj5u.com熱心網友回復:
嘗試更改選擇器以定位檔案,如下所示:
$(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();洗掉了附加了偵聽器的元素,因此新元素在附加后沒有點擊偵聽器。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/343685.html
上一篇:ajax沒有得到值?
