如何用JavaScript实现POS系统表格商品数量自增而非新增行
POS系统商品重复行处理方案
问题分析
原代码的核心问题:
- 点击添加按钮直接新增空行,未提前判断商品是否已存在于表格中;
- 商品选择后的重复校验逻辑错误,无法正确定位已有商品的数量单元格,且重复绑定事件导致逻辑混乱。
修正后的完整代码
HTML部分
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <button class="btnaddstockTransfer" type="button"> 添加库存转移行 </button> <div style="overflow-x:auto"> <table id="stockTransfer" class="table"> <thead> <tr> <th style="color:blue">搜索商品(名称/编码)</th> <th style="color:blue">数量</th> </tr> </thead> <tbody> </tbody> </table> </div>
JavaScript部分
$(document).ready(function() { // 添加空行按钮事件 $(document).on('click', '.btnaddstockTransfer', function() { const html = ` <tr> <td> <div class="search-box"> <input class="form-control is-warning stock" type="text" name="stock[]" placeholder="按名称或编码搜索"> <div class="result"></div> </div> </td> <td> <input class="form-control qty" type="text" name="qty[]" required size="2"> </td> </tr> `; $('#stockTransfer tbody').append(html); }); // 实时搜索事件(仅绑定一次) $(document).on('keyup input', '.search-box input[type="text"]', function() { const inputVal = $(this).val(); const resultDropdown = $(this).siblings(".result"); if (inputVal.length) { // 模拟搜索结果,实际项目替换为AJAX请求 resultDropdown.html("<p>Result 1</p><p>Result 2</p>"); } else { resultDropdown.empty(); } }); // 选择搜索结果事件 $(document).on("click", ".result p", function() { const selectedStock = $(this).text().trim(); const searchBox = $(this).parents(".search-box"); const currentRow = searchBox.closest('tr'); // 清空搜索结果并填充商品名 searchBox.find('.stock').val(selectedStock); $(this).parent(".result").empty(); // 检查表格中是否已存在该商品 let stockExists = false; $('#stockTransfer tbody tr').each(function() { const existingStock = $(this).find('.stock').val().trim(); if (existingStock === selectedStock && $(this).get(0) !== currentRow.get(0)) { // 找到已有商品,数量自增1 const qtyInput = $(this).find('.qty'); qtyInput.val(parseInt(qtyInput.val() || 0) + 1); stockExists = true; return false; // 终止循环 } }); // 若商品不存在,设置当前行数量为1;若存在,移除当前空行 if (!stockExists) { currentRow.find(".qty").val(1); } else { currentRow.remove(); } }); });
代码说明
- 事件绑定优化:将搜索和商品选择事件从添加按钮的点击事件中移出,避免每次添加行都重复绑定事件,减少无效触发;
- 重复商品判断逻辑:
- 选择商品后,遍历表格所有行,对比商品名称;
- 若找到同款商品,直接将对应行的数量值加1;
- 若未找到,则保留当前行并设置数量为1;若已存在,则移除当前新增的空行;
- 冗余代码清理:移除原表格中无意义的空行,保持结构整洁。
内容的提问来源于stack exchange,提问作者GoodNews Carrier
相关产品推荐
相关产品推荐

