我們從後臺取出數據後通常用<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",
});
}
})
}