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

如何实现点击按钮切换数组内对象内容并同步更新DOM?

解决点击按钮切换词汇内容的问题

问题说明

开发英语词汇学习工具时,点击按钮仅能显示数组第一个对象的内容,需要实现每次点击切换到下一个对象并更新DOM内容的功能。

解决方案

要实现切换功能,核心是追踪当前显示的词汇索引,每次点击更新索引并渲染对应内容,具体步骤如下:

  • 新增一个索引变量,初始值设为0,用来记录当前展示的是数组中第几个词汇对象。
  • 移除reload函数里对数组的map操作——没必要把每个字段单独提取成新数组,直接通过索引访问原数组的对象即可。
  • 每次点击按钮后,先更新DOM内容,再把索引加1;当索引超过数组长度时,重置为0,实现循环切换。

修改后的完整代码

document.addEventListener('DOMContentLoaded', function () {
    const wordy = document.querySelector('#word');
    const palabraHTML = document.querySelector('#palabra');
    const sentence = document.querySelector('#sen');
    const oracion = document.querySelector('#oracion');
    const btnReload = document.querySelector('#button');

    // 新增索引变量,追踪当前显示的词汇位置
    let currentIndex = 0;

    btnReload.addEventListener('click', reload);

    function reload() {
        // 直接通过当前索引获取对应的词汇对象
        const currentWord = words[currentIndex];

        // 更新DOM内容
        wordy.textContent = currentWord.word;
        palabraHTML.textContent = currentWord.palabra;
        sentence.textContent = currentWord.sentence;
        oracion.textContent = currentWord.oracion;

        // 更新索引,到达数组末尾时重置为0
        currentIndex = (currentIndex + 1) % words.length;
    }

    const words = [
        {
            word: "the",
            palabra: "El / Los",
            sentence: "The sun is up",
            oracion: "El sol ha salido"
        },
        {
            word: "be",
            palabra: "Ser / Estar",
            sentence: "Don't be sad",
            oracion: "No estes trsite"
        },
        {
            word: 'as',
            palabra: 'como (adv.)',
            sentence: 'He used me as a guinea pig',
            oracion: 'Me utilizó como conejillo de indias'
        },
        {
            word: 'will',
            palabra: '(futuro), voluntad',
            sentence: 'Will she come?',
            oracion: '¿Vendrá? (Ella)'
        }
    ];

    // 页面加载时自动渲染第一个词汇
    reload();
});

额外优化说明

  • 新增页面加载时自动调用reload()的逻辑,无需点击按钮就能显示第一个词汇,提升用户体验。
  • 使用(currentIndex + 1) % words.length更新索引,比手动判断索引是否越界更简洁,自动实现循环切换。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 03:25:33