点击新增按钮结合输入值控制多组货运记录div显示隐藏实现咨询
修正后的实现方案
1. 首先调整HTML结构,解决重复ID、按钮重复渲染的问题
你原有代码把按钮写在循环内部会生成20个重复按钮,且所有输入框和按钮都用了相同ID,不符合DOM规范,调整后代码如下:
<!-- 20条记录循环部分 --> <div th:each="freight, itemStat : *{freightsDto}" class="freight-item"> <div class="row mtp"> <div class="col-sm-8 w-50 desc"> <label class="row">Item description</label> <input class="row form-control input-desc" type="text" th:field="*{freightsDto[__${itemStat.index}__].name}" required="required"> </div> </div> <hr> </div> <!-- 新增按钮统一放在循环外部 --> <div id="toggleBtn" class="row mtp"> <button class="col-sm-12"> Add more shipments </button> </div>
2. 添加CSS实现默认显隐逻辑
/* 默认隐藏所有描述输入框容器 */ .desc { display: none; } /* 仅第一个条目默认显示 */ .freight-item:first-child .desc { display: block; }
3. 添加JavaScript实现交互逻辑
document.addEventListener('DOMContentLoaded', function() { const addBtn = document.querySelector('#toggleBtn button'); const freightItems = document.querySelectorAll('.freight-item'); let currentShowIndex = 0; // 记录当前已显示的最大索引,默认第一个已显示 addBtn.addEventListener('click', function() { // 已经显示到最后一条,直接返回 if (currentShowIndex >= freightItems.length - 1) { alert('最多可添加20条货运信息'); return; } // 获取当前最后一个显示的输入框的值 const lastInput = freightItems[currentShowIndex].querySelector('.input-desc'); const inputValue = lastInput.value.trim(); // 输入框有值才显示下一条 if (inputValue) { currentShowIndex++; freightItems[currentShowIndex].querySelector('.desc').style.display = 'block'; // 自动聚焦到新显示的输入框,提升使用体验 freightItems[currentShowIndex].querySelector('.input-desc').focus(); } else { alert('请先填写当前货运信息的物品描述'); lastInput.focus(); } }); });
逻辑说明
- 预渲染的20条记录默认仅第一条显示,其余全部隐藏
- 每次点击添加按钮时,优先校验当前已显示的最后一条输入框是否有有效内容
- 校验通过后自动显示下一条记录的输入框,最多显示到第20条
内容的提问来源于stack exchange,提问作者Tyler Durden
相关产品推荐
相关产品推荐

