如何实现点击按钮逐行添加月份,至April后禁用新增功能?
问题修正方案
核心问题分析
原代码存在三个关键问题:
- 直接拼接整个
months数组到表格单元格,导致所有月份一次性显示在同一行 - 使用
months++来"计数"是错误操作(数组无法用自增运算符),没有跟踪当前已添加的月份索引 - 未添加停止判断,添加完所有月份后仍可继续点击;同时删除按钮的HTML未在代码中体现,且
counter变量未定义
修正后的完整代码
<a class="btn btn-primary rounded-0 btn-block" id="insertRow" href="#">Add new row</a> <!-- 补充完整表格结构示例 --> <table class="table"> <thead> <tr> <th scope="row">Month</th> <th>First Name</th> <th>Action</th> </tr> </thead> <tbody> <!-- 新增行将插入到这里 --> </tbody> </table> <script> $(function () { // 月份数组 const months = ["January", "February", "March", "April"]; // 跟踪当前已添加的月份索引,从0开始 let currentIndex = 0; $("#insertRow").on("click", function (event) { event.preventDefault(); // 判断是否已添加完所有月份,是则直接返回 if (currentIndex >= months.length) { return; } const newRow = $("<tr>"); let cols = ''; // 取当前索引对应的单个月份 cols += `<th scope="row">${months[currentIndex]}</th>`; cols += '<td><input class="form-control rounded-0" type="text" name="firstname" placeholder="First name"></td>'; // 添加删除按钮(用class避免重复id) cols += '<td><button class="btn btn-danger deleteRow">Delete</button></td>'; newRow.append(cols); // 将新行插入到表格tbody中(更规范) $("table tbody").append(newRow); // 索引自增,准备下一个月份 currentIndex++; }); // 删除行事件:监听class为deleteRow的按钮 $("table").on("click", ".deleteRow", function (event) { // 可选:删除后允许重新添加该行,调整currentIndex const deletedMonth = $(this).closest("tr").find("th").text(); const monthIndex = months.indexOf(deletedMonth); if (monthIndex !== -1 && monthIndex < currentIndex) { currentIndex--; } // 删除当前行 $(this).closest("tr").remove(); }); }); </script>
关键改动说明
- 新增
currentIndex变量跟踪已添加的月份位置,每次点击后自增 - 点击时先判断索引是否超出数组长度,超出则停止添加操作
- 拼接单元格时取数组中单个月份,而非整个数组
- 为每行添加class为
deleteRow的删除按钮(避免重复id),修正删除逻辑 - 可选:删除行时调整
currentIndex,允许重新添加已删除的月份(不需要可删除对应代码) - 规范表格插入位置,将新行插入到
tbody中而非直接添加到table标签
内容的提问来源于stack exchange,提问作者Robbie
相关产品推荐
相关产品推荐

