我们从后台取出数据后通常用<c:forEach>在前台循环生成数据行进行显示,该如何通过checkbox实现对数据行批量删除呢?思路如下:
点击按钮,遍历checkbox,判断是否选中,若选中,则将该行数据id传入后台进行删除。代码如下:
<table>
<tr class="tb_title" style="text-align: center;">
<td width="20%" style="font-size: 15px;"><b>商品图片</b></td>
<td width="40%" style="font-size: 15px;"><b>商品介绍</b></td>
<td width="20%" style="font-size: 15px;"><b>商品价格</b></td>
<td width="20%" style="font-size: 15px;"><b>操作</b></td>
</tr>
<c:forEach var="n" items="${unreceiveds}" >
<tr style="text-align: center;">
<td width="20%"><img src="${n.getPicone()}" height="120" width="120" style="margin-top: 5px;"/></td>
<td width="40%">${n.getGoodstitle()}</td>
<td width="20%">${n.getGoodsprice()}元</td>
<td width="20%"><input type="checkbox" class="xuanzhong" value="${n.getUnreceivedid()}" id="${n.getUnreceivedid()}"></td>
</tr>
</c:forEach>
</table>
<button οnclick="receiveGoods()">批量删除</button>
js代码
function receiveGoods(){
var trs = $("table").find("tr"); //获取表格每一行
trs.each(function() { // 遍历
var isChecked = $(this).find(".xuanzhong").prop("checked"); // 获取当前行checkbox选择状态;
if(isChecked == true || isChecked == "true") { // 如果选中(后者是为了兼容火狐)
var unreceivedid = $(this).find(".xuanzhong").attr("id"); // checkbox的id
$.ajax({
url:"/DepartmentStore/goods/receiveGoods.do",//提交到后台进行删除
type:"post",
data:{ unreceivedid:unreceivedid },
dataType: "json",
});
}
})
}