如何用原生JavaScript区分同class多行并显示对应库存?
问题根源
你的代码每次选择产品时,会遍历所有带.qte类的单元格并更新匹配的库存,这就导致所有行都会显示最后选中产品的库存。另外还有几个小问题:重复的id="pick"(ID必须唯一)、未声明的全局变量myObj、冗余的this.product赋值。
修复方案
1. 修改addItem函数(修复重复ID,传递当前元素)
function addItem() { items++; var html = "<tr>"; html += "<td><input type='text' class='form-control product-input' name='product[]' list='produit' onchange='showAmount(this.value, this)' ><datalist id='produit'> <?php foreach ($productinfo as $req) { ?><option value='<?php echo $req['NomArt']; ?>'><?php echo $req['NomArt']; } ?></option></datalist></td>"; html += "<td class='text-center qte'></td>"; html += "<td><input type='number' class='form-control' name='qte[]'></td>"; html += "<td><button type='button' class='btn btn-danger' onclick='remove(this);'><i class='fa fa-close'></i></button></td>"; html += "</tr>"; var row = document.getElementById("tbody").insertRow(); row.innerHTML = html; }
2. 重构showAmount函数(只更新当前行的库存)
function showAmount(productName, inputElement) { // 找到当前input所在的表格行 const currentRow = inputElement.closest('tr'); // 定位到当前行的.qte单元格 const qteCell = currentRow.querySelector('.qte'); if(productName === '') { qteCell.innerHTML = " "; return; } const xmlhttp = new XMLHttpRequest(); xmlhttp.onload = function(){ // 声明变量,避免全局污染 const myObj = JSON.parse(this.responseText); // 找到匹配的产品 const matchedProduct = myObj.find(item => item.NomArt === productName); if(matchedProduct) { qteCell.innerHTML = matchedProduct.Qte; } else { qteCell.innerHTML = "无库存"; } } xmlhttp.open("GET", "templates/Client/products.json", true); xmlhttp.send(); }
关键改动说明
- 传递当前元素:调用
showAmount时传入this(当前input元素),精准定位到当前行,而非操作所有行。 - 精准定位单元格:用
closest('tr')找到当前行,再用querySelector('.qte')获取该行的库存单元格,只更新目标单元格。 - 优化产品匹配:用
Array.find()替代嵌套循环,逻辑更简洁高效。 - 修复无效ID:去掉重复的
id="pick",避免DOM ID冲突问题。 - 变量声明规范:用
const声明myObj等常量,避免全局变量污染。
内容的提问来源于stack exchange,提问作者nas213sim
相关产品推荐
相关产品推荐

