动态追加表格行中下拉列表数据填充异常问题排查
解决动态添加表格行时下拉列表数据错位的问题
我一眼就看出问题所在了——你在AJAX成功回调里的DOM拼接逻辑出错了,导致下拉选项没有被插入到对应的<select>标签内部,反而直接被追加到了表格主体(#item_body)中,所以才会出现数据跑到其他行的情况。
原代码的核心问题
你先向#item_body追加了包含<select>开头的HTML片段,然后循环时又直接把<option>追加到#item_body,这时候这些选项就成了表格的直接子元素,自然不会出现在目标下拉框里。另外还有两个小问题:
- 所有动态生成的元素都用了相同的
id(比如item_name),这会造成DOM ID冲突,后续操作会出问题 - 下拉选项的
value是空的,提交表单时无法获取有效数据
修正后的代码方案
推荐用jQuery元素操作的方式来构建行,这样能精准控制选项插入到对应的下拉框中,同时解决ID冲突和表单提交的问题:
$('td #add_fields').click(function(){ item_count++; var url = baseURL+'interfaces/population'; $.ajax({ type: "GET", url: url, data:'', dataType: 'json', success: function(res){ // 1. 构建完整的表格行元素,用class替代重复id,name改为数组格式方便表单提交 var $newRow = $(` <tr id="item_row_${item_count}"> <th>${item_count}</th> <td> <select class="form-control item_name" name="item_name[]" style="width:150px;"> <option value="none" selected disabled>Select Item</option> </select> </td> <td><input type="text" name="qty_unit[]" class="form-control qty_unit"></td> <td><input type="text" name="price_p_u[]" class="form-control price_p_u"></td> <td></td> <td><input type="text" name="qty[]" class="form-control qty"></td> <td><input type="text" name="total_price[]" class="form-control total_price"></td> <td><input type="button" class="btn btn-danger remove_fields" value="X"></td> </tr> `); // 2. 获取当前行的下拉框元素 var $select = $newRow.find('.item_name'); // 3. 循环数据,将选项插入到当前下拉框中 $.each(res, function(index, item){ // 建议使用item的ID作为value,原代码value为空无法提交有效数据 $select.append(`<option value="${item.item_id}">${item.item_name}</option>`); }); // 4. 将组装好的行追加到表格 $('#item_body').append($newRow); } }); });
额外说明
如果你习惯用字符串拼接的方式,也可以先把所有HTML(包括选项)拼接成一个完整字符串,再一次性追加到#item_body,避免多次DOM操作:
success: function(res){ var html = `<tr id="item_row_${item_count}"> <th>${item_count}</th> <td> <select class="form-control item_name" name="item_name[]" style="width:150px;"> <option value="none" selected disabled>Select Item</option>`; // 循环拼接选项 $.each(res, function(i, item){ html += `<option value="${item.item_id}">${item.item_name}</option>`; }); // 拼接剩余HTML html += `</select> </td> <td><input type="text" name="qty_unit[]" class="form-control qty_unit"></td> <td><input type="text" name="price_p_u[]" class="form-control price_p_u"></td> <td></td> <td><input type="text" name="qty[]" class="form-control qty"></td> <td><input type="text" name="total_price[]" class="form-control total_price"></td> <td><input type="button" class="btn btn-danger remove_fields" value="X"></td> </tr>`; $('#item_body').append(html); }
你的Model代码get_item_data_app()是没问题的,只要它能正确返回包含item_id(如果有的话)和item_name的JSON数据,修正后的前端代码就能正常渲染下拉选项。
内容的提问来源于stack exchange,提问作者mcprilla79
相关产品推荐
相关产品推荐

