[英]Unable to remove table row using jQuery
我想删除表行,数据从数据库中删除,但为什么没有从 html 表中删除。 任何解决方案表示赞赏!
$('#datatables').on('click', '.delete_department', (e) => {
var id = e.currentTarget.id;
$.ajax({
type: 'POST',
url: BASE_URL + 'admin/delete_department',
data: { id: id },
success: (response) => {
$('#datatables').closest('tr').remove();
}
});
});
这是使用 PHP 生成的 HTML 表
<table id="datatables" class="css-serial text-center table table-striped table-no-bordered table-hover dataTable dtr-inline">
<thead>
<tr role="row">
<th>#</th>
<th>Department</th>
<th>Action</th>
</tr>
</thead>
<tfoot>
<tr>
<th rowspan="1" colspan="1">#</th>
<th rowspan="1" colspan="1">Department</th>
<th rowspan="1" colspan="1">Action</th>
</tr>
</tfoot>
<tbody>
<?php foreach ($departments as $key => $department) { ?>
<tr>
<td>
<p data-letters="<?php echo ucwords(substr($department['department'], 0, 1)); ?>"></p>
</td>
<td><?php echo $department['department'] ?></td>
<td>
<button class='edit_department btn btn-danger btn-link' id='<?php echo $department['id'] ?>'><i class='material-icons'>edit</i></button>
<button class='delete_department btn btn-danger btn-link' id='<?php echo $department['id'] ?>'><i class='material-icons'>close</i></button>
</td>
</tr>
<?php } ?>
</tbody>
</table>
保存单击的按钮元素的引用,然后使用closest
获取tr
。
$('#datatables').on('click', '.delete_department', function(e) {
const that = $(this);
var id = e.currentTarget.id;
$.ajax({
type: 'POST',
url: BASE_URL + 'admin/delete_department',
data: { id: id }, // or just use shorthand notation { id }
success: (response) => {
$(that).closest('tr').remove();
}
});
});
注意-可以使用function()
来获取单击元素的引用,而不是使用箭头函数。
让_this = $(this); 在上面声明var id = e.currentTarget.id;
并在成功函数_this.parent('tr')。remove();中设置以下行
并将成功用作功能成功:功能(响应){
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.