Flutter中使用Dart实现按钮点击时逐条遍历展示列表项
单条遍历展示列表的实现方案
你贴的列表数据里混了多余的enter code here标记,先修正为合法的JS数组格式:
const listData = [ { "id": 1, "name": "quidem molestiae enim", "date": "2021, Jun, 20-24" }, { "id": 2, "name": "sunt qui excepturi placeat culpa", "date": "2019, Feb, 20-24" }, { "id": 3, "name": "omnis laborum odio", "date": "2021, Jan, 20-26" } ]
核心实现逻辑
不需要循环渲染整个列表,只需要维护一个指向当前展示位置的索引变量,每次点击按钮修改索引值,再根据索引渲染对应条目即可,整体逻辑非常轻量:
- 定义状态变量
currentIndex,初始值设为0,对应列表的第一个条目 - 编写渲染逻辑:根据索引直接从列表中取出对应对象,把它的
name、date字段值填充到页面的展示区域 - 给按钮绑定点击事件:每次触发就按规则更新
currentIndex,可以按需选择两种边界处理方式:到列表末尾后循环回第一条,或是停在最后一条并禁用按钮
可直接运行的原生JS实现
<!-- 单条目展示区域 --> <div class="display-container"> <h3 id="itemName"></h3> <p id="itemDate"></p> </div> <!-- 遍历触发按钮 --> <button id="nextBtn">查看下一条</button> <script> // 修正后的列表数据 const listData = [ { "id": 1, "name": "quidem molestiae enim", "date": "2021, Jun, 20-24" }, { "id": 2, "name": "sunt qui excepturi placeat culpa", "date": "2019, Feb, 20-24" }, { "id": 3, "name": "omnis laborum odio", "date": "2021, Jan, 20-26" } ] // 初始化当前展示索引,默认展示第一条 let currentIndex = 0 // 根据当前索引更新页面展示内容 function renderCurrentItem() { const currentItem = listData[currentIndex] document.getElementById('itemName').innerText = currentItem.name document.getElementById('itemDate').innerText = currentItem.date } // 页面首次加载时渲染第一条内容 renderCurrentItem() // 绑定按钮点击事件 document.getElementById('nextBtn').addEventListener('click', () => { // 边界规则1:到达最后一条后,自动循环回到第一条 currentIndex = (currentIndex + 1) % listData.length // 边界规则2(不循环的场景,替换上面一行代码即可):到达最后一条后禁用按钮,不再触发遍历 // currentIndex = Math.min(currentIndex + 1, listData.length - 1) // if (currentIndex === listData.length - 1) { // document.getElementById('nextBtn').disabled = true // } // 索引更新后重新渲染对应条目 renderCurrentItem() }) </script>
如果使用Vue/React这类响应式框架,实现逻辑完全一致,只需要把currentIndex声明为响应式状态,框架会自动监听值变化更新页面内容,不需要手动操作DOM修改文本。
内容的提问来源于stack exchange,提问作者Nsamba Isaac
相关产品推荐
相关产品推荐

