如何使用JS删除两个tr行 购物车删除商品时店铺名称行未删除问题
购物车删除功能店铺行未移除问题修复方案
问题根因
- 现有代码仅处理了商品所在行的删除逻辑,未关联校验对应店铺下是否还有剩余商品,因此店铺所在的
<tr>行不会被同步删除 - 从HTML结构看,店铺行存放在
<thead>标签中,商品行存放在同个表格的<tbody>标签中,二者属于同个表格的不同分区,删除商品行时不会自动关联触发父级店铺行的删除操作 - 现有提交参数存在拼写错误:
pdoductid应为productid,建议同步修正避免后续接口报错
修复方案
步骤1:新增店铺关联标识
修改HTML结构,给店铺行增加data-shop-id属性存储店铺唯一ID,同店铺下的所有商品行也新增相同值的data-shop-id属性,方便二者关联匹配:
<table> <thead> <!-- 店铺行新增data-shop-id属性 --> <tr data-row-id="item.id" data-shop-id="当前店铺唯一ID"> <td colspan="4" style="color: #d53434">Shop: <strong>Shop name</strong></td> </tr> </thead> <tbody> <!-- 对应店铺下的所有商品行新增相同值的data-shop-id属性 --> <tr role="row" data-row-id="item2.id" data-shop-id="当前店铺唯一ID"> ... <td><button data-button-name="delete">删除</button></td> </tr> </tbody> </table>
步骤2:修改删除逻辑,增加店铺行校验
在postData的删除成功回调中增加店铺剩余商品校验逻辑:
basketContainer.on('click', 'button[data-button-name="delete"]', function() { var o = $(this); var t = o.closest("tr"); var currentRow = getCurrentRow(t); if (currentRow == null) { return; } postData(t, currentRow.index, { "basketid": currentRow.id, "productid": currentRow.ProductID, // 修正拼写错误 "count": 0, "cmdtype": cmdTypes.Delete }, function() { // 删除当前商品行 t.remove(); // 获取当前商品所属店铺ID const shopId = t.attr("data-shop-id"); // 统计该店铺下剩余商品行数量 const remainGoods = $(`tbody tr[data-shop-id="${shopId}"]`).length; // 无剩余商品时删除对应店铺行 if (remainGoods === 0) { $(`thead tr[data-shop-id="${shopId}"]`).remove(); } }); });
内容的提问来源于stack exchange,提问作者Shqiptar
相关产品推荐
相关产品推荐

