You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript中实现点击按钮逐个显示数组元素

解决点击按钮单元素切换的问题

你的问题出在show函数里用了forEach遍历整个数组,所以每次点击都会把所有元素的内容拼在一起显示。要实现每次点击只显示一个元素,需要跟踪当前显示的元素索引,每次点击更新索引并渲染对应元素。

修改后的代码

const arr = [
  {
    img: "https://www.tourmyindia.com/blog//wp-content/uploads/2021/10/Best-Places-to-Visit-in-Bhopal-MP-Sanchi-Stupa.jpg",
    place: "BHOPAL",
    state: "MADHYA PRADESH",
  },
  {
    img: "https://www.tourmyindia.com/blog//wp-content/uploads/2021/10/Best-Places-to-Visit-in-Bhopal-MP-Sanchi-Stupa.jpg",
    place: "MUMBAI",
    state: "MAHARASHTRA",
  },
];

// 跟踪当前显示的元素索引,初始指向第一个元素
let currentIndex = 0;

function show() {
  // 根据当前索引获取单个数组元素
  const item = arr[currentIndex];
  // 生成单个元素的HTML结构,补上图片标签
  const cluster = `
    <img src="${item.img}" alt="${item.place}" />
    <h1>${item.place}</h1>
    <div class="vt-bar"></div>
    <h3>${item.state}</h3>
    <div class="arrow">
        <i class="ri-arrow-left-line"></i>
        <div class="hz-bar"></div>
        <i class="ri-arrow-right-line"></i>
    </div>
  `;
  document.getElementById("cluster").innerHTML = cluster;
};

document.getElementById("random").addEventListener("click", function(){
  // 更新索引:点击后切换到下一个元素,超出数组长度则回到第一个(循环切换)
  currentIndex = (currentIndex + 1) % arr.length;
  show();
});

// 可选扩展:给左右箭头添加切换功能
document.querySelector(".ri-arrow-left-line")?.addEventListener("click", () => {
  // 左箭头逻辑:索引减1,加数组长度再取模避免负数
  currentIndex = (currentIndex - 1 + arr.length) % arr.length;
  show();
});

document.querySelector(".ri-arrow-right-line")?.addEventListener("click", () => {
  currentIndex = (currentIndex + 1) % arr.length;
  show();
});

关键改动说明

  • 新增currentIndex变量:用来记录当前显示元素在数组中的位置,初始值为0(指向第一个元素)。
  • 重构show函数:不再遍历整个数组,而是直接通过currentIndex获取单个元素,生成对应HTML,同时补上了原代码缺失的图片展示标签。
  • 点击事件逻辑:通过(currentIndex + 1) % arr.length实现索引循环更新——当索引到达最后一个元素后,再加1会自动回到0,实现循环切换效果。
  • 可选箭头功能:给左右箭头添加了点击切换逻辑,左箭头索引减1时通过+ arr.length避免出现负数索引。

内容的提问来源于stack exchange,提问作者Yash kolte

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 19:40:38