HTML:
<table class="table table-hover">
<thead>
<tr>
<th><?php echo __('ID');?></th>
<th><?php echo __('File Name');?></th>
<th><?php echo __('Operation');?></th>
</tr>
</thead>
<tbody>
<?php if( ! empty($files)) : ?>
<?php foreach($files as $id => $file) :?>
<tr>
<td><?php echo $id+1; ?></td>
<td><?php echo $file; ?></td>
<td>
<button class="btn btn-sm btn-default action-edit" title="" >
<i class="fa fa-edit"></i>
</button>
<button class="btn btn-sm btn-default action-delete" data-table="#admin-delete-pages" data-toggle="popup" title="删除" >
<i class="fa fa-trash-o"></i>
</button>
</td>
<td><input type='hidden' name='file_name' value="<?php echo $file;?>"></td>
</tr>
<?php endforeach; ?>
<?php else : ?>
<tr>
<td colspan='7'><?php echo __('No result is available');?></td>
</tr>
<?php endif;?>
</tbody>
</table>
需求说明:点击删除按钮时,通过ajax无刷新删除当前的这一行,并用jQuery删除页面中这一行记录
jQuery代码如下:
$(".action-delete").click(function(){
var statu = confirm("您确定要删除此版本吗?");
if(!statu){
return false;
}
var submit_data = {file_name:$(this).parent().next().children().val()};
$.post("/admin/backup/delete",
submit_data,
function(data){
if(data.success == true){
$(this).parent("tr").remove();
alert(data.msg);
}else{ alert(data.msg); }
},
"json");
});
后来点击去测试,发现没有效果,后来搜索了一下,在stackoverflow看到一个相似的问题,主要有两个问题:
这是原话(
parent
only travels up 1 level. And since .removeItem is within the form, you needclosest
.
And like foxx was saying, by using this
inside the done callback, you're not targetting the dom element. So you have to assign it as a local variable (var removeItemEl = $(this);
).
1.parent只能向上搜索一层,而在此我用了parent("tr")是希望能向上搜索得到上两层的tr元素,这是不可以的。而需要用到closest(selector),获得匹配选择器的第一个祖先元素
2.在回调函数中,运用$(this)是无效的,需要先把这个声明为一个局部变量再去使用。
修改后代码如下:
$(".action-delete").click(function(){
var statu = confirm("您确定要删除此版本吗?");
if(!statu){
return false;
}
var submit_data = {file_name:$(this).parent().next().children().val()};
var $button = $(this);
$.post("/admin/backup/delete",
submit_data,
function(data){
if(data.success == true){
alert(data.msg);
$button.closest("tr").remove();
}else{
alert(data.msg);
}
},
"json");
});