如何实现表格不同行插入不同值?新增行后内容同步异常求助
表格新增行后选择产品时所有行同步变化的问题
问题描述
需要为表格不同行插入不同值,但当前添加行并插入项目时,第一行内容会与第二行同步变化。
现有代码
新增行逻辑
var count = $(".itemRow").length; $(document).on("click", "#addRows", function () { count++; var htmlRows = ""; htmlRows += "<tr>"; htmlRows += '<td><input class="itemRow" type="checkbox"></td>'; htmlRows += '<td><div style="display: flex"><input style="width:60%; margin-top:0.5%; margin-left:0.5%" type="text" name="productName[]" id="productName_'+ count +'" class="form-control" autocomplete="off">  <p class="item-select items" style="padding-top:1%"> or <a href="#" data-target="#myModal" data-row-id="' + count + '">select a product</a></p></div></td>'; htmlRows += '<td><input type="number" name="quantity" id="quantity_' + count + '" class="form-control quantity" autocomplete="off"></td>'; htmlRows += '<td><input type="number" name="price" id="price_' + count + '" class="form-control price" autocomplete="off"></td>'; htmlRows += '<td><input type="number" name="total" id="total_' + count + '" class="form-control total" autocomplete="off"></td>'; htmlRows += "</tr>"; $("#invoiceItem").append(htmlRows); });
模态框选择产品逻辑(原代码)
$(document).on("click", "#modal", function (){ var productName = $("#productname").val(); var nameProduct = productName.split('||')[0]; var pPrice = productName.split('||')[1]; $("[id^=productName_]").val(nameProduct); $("[id^=price_]").val(pPrice); });
异常情况说明
- 第一行初始状态:表格第一行仅有空白输入框,未填入任何内容
- 新增第二行并插入项目后的异常状态:选择产品后,第一行和第二行的产品名称、价格同步变成选中的内容
- 预期效果:每一行可独立选择不同产品,各行内容互不影响
问题原因与解决方案
问题原因
原模态框代码中使用了$("[id^=productName_]")和$("[id^=price_]")选择器,会匹配所有id以productName_和price_开头的输入框,导致选择产品时所有行的对应输入框被同时赋值,造成同步变化的问题。
解决方案
通过记录当前触发模态框的行ID,仅对该行的输入框赋值:
- 给新增行中的「select a product」链接添加
data-row-id属性,绑定当前行的唯一标识 - 点击链接时记录当前行ID
- 模态框确认选择时,根据记录的行ID更新对应输入框的内容
修改后的模态框相关代码:
// 存储当前选中的行ID let currentRowId = null; // 监听选择产品链接的点击事件,记录行ID $(document).on("click", ".item-select a", function (){ currentRowId = $(this).data('row-id'); }); // 修改模态框确认逻辑,仅更新当前行的输入框 $(document).on("click", "#modal", function (){ var productName = $("#productname").val(); var nameProduct = productName.split('||')[0]; var pPrice = productName.split('||')[1]; // 仅对当前选中行的输入框赋值 $("#productName_" + currentRowId).val(nameProduct); $("#price_" + currentRowId).val(pPrice); });
同时修复新增行代码中div样式的语法错误(移除多余的"),确保HTML结构正确。
内容的提问来源于stack exchange,提问作者Meow
相关产品推荐
相关产品推荐

