JS中HTML元素内+count+除首个外均返回NaN的问题求助
解决方法
1. 修复HTML字符串语法错误
你的HTML字符串里存在一个多余的</div>(位于textarea标签之后),这会破坏DOM结构,导致后续元素的属性解析异常。需要移除这个多余的闭合标签。
2. 正确插入生成的行到DOM中
原代码创建了<tr>元素但未使用,也没有将生成的HTML内容添加到页面表格中,导致新行无法显示,自然无法通过$_POST获取对应数据。需要补充DOM插入逻辑。
3. 确保count变量的数值一致性
全局count初始为数字类型,每次调用new_link()时自增,本身不会出现NaN,但要避免其他代码意外将其修改为非数值类型。
修正后的完整代码
var count = 1; function new_link() { count++; // 获取表格的tbody容器(需确保页面表格包含tbody标签) const tbody = document.querySelector('table tbody'); if (!tbody) return; // 修复后的HTML字符串,移除多余的</div> var rowContent = '<th scope="row" class="product-id">' + count + '</th><td class="text-start"><div class="mb-2"><input class="form-control bg-light border-0" type="text" name="productName-' + count + '" id="productName-' + count + '" placeholder="Product Name"></div><textarea class="form-control bg-light border-0" id="productDetails-' + count + '" rows="2" placeholder="Product Details"></textarea></td><td><input class="form-control bg-light border-0 product-price" type="number" id="productRate-' + count + '" step="0.01" placeholder="$0.00"></td><td><div class="input-step"><button type="button" class="minus">–</button><input type="number" class="product-quantity" id="product-qty-' + count + '" value="0" readonly><button type="button" class="plus">+</button></div></td><td class="text-end"><div><input type="text" class="form-control bg-light border-0 product-line-price" id="productPrice-' + count + '" value="$0.00" placeholder="$0.00" /></div></td><td class="product-removal"><a class="btn btn-success">Delete</a></td>'; // 创建tr元素并填充内容 const newRow = document.createElement("tr"); newRow.id = count; newRow.className = "product"; newRow.innerHTML = rowContent; // 将新行添加到表格中 tbody.appendChild(newRow); }
关键说明
- 移除多余的
</div>后,DOM结构恢复正常,所有包含count的name、id属性都会正确生成数值后缀,不会出现解析异常导致的NaN。 - 新增的DOM插入逻辑确保新生成的行能显示在页面上,表单提交时这些输入框的数据才能被
$_POST正常捕获。 - 简化了原代码中重复创建
<tr>的冗余逻辑,让代码更清晰易维护。
内容的提问来源于stack exchange,提问作者d4g5h7
相关产品推荐
相关产品推荐

