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

JavaScript实现点击按钮重置已打乱多语言JSON的遍历索引

功能实现修正代码

HTML 代码(和原代码一致无改动)

<div class="container">
  <div>
    <div id="title"></div>
  </div>
  <button id="refbtn">WINE</button>
</div>

JavaScript 修正代码

// 检测浏览器语言
var userLang = navigator.language || navigator.userLanguage; 
console.log("浏览器语言为: " + userLang);

var alcoscroll = {
    "wine": [{
        "en": "Wine Drink 1",
        "es": "Vino 1",
    }, {
        "en": "Drink 2",
        "es": "Vino 2",
    }, {
        "en": "Drink 3",
        "es": "Vino 3",
    }, {
        "en": "Drink 4",
        "es": "Vino",
    }]
};

// 打乱排序,初始化后不会再重新排序
alcoscroll.wine.sort(function () {return Math.random() - 0.5;});
console.log(alcoscroll);

var index = 0; // 初始索引
var maxx  = alcoscroll.wine.length - 1; // 最大索引值
var next = document.getElementById('refbtn');
var title = document.getElementById('title'); // 提前获取title元素,原代码漏了这步会报错

displayItem(alcoscroll.wine[index]);

// 只绑定一次点击事件,不要重复绑定
next.addEventListener('click', function() {
    // 点击时先判断索引是否到最大值,到了就重置为0,否则索引+1
    if (index >= maxx) {
        index = 0;
    } else {
        index++;
    }
    displayItem(alcoscroll.wine[index]);
});

console.log("最大索引值为: " + maxx)

function displayItem(item) {
    // 根据语言切换展示内容
    if (userLang === "en-US") {
        title.innerText = item.en;
    } else {
        title.innerText = item.es;
    }
    console.log("当前索引值为: " + index)
}
主要改动说明
  • 提前获取titleDOM元素,避免原代码直接调用title变量报错
  • 移除了displayItem函数内重复绑定点击事件的逻辑,避免多次触发回调的问题
  • 把索引判断逻辑放到点击事件回调内:每次点击先判断当前索引是否等于最大索引,是就重置为0,否则索引自增,实现循环遍历的效果
  • 移除了原代码里无用的intitem变量,直接用全局维护的index变量做判断即可,避免类型匹配错误的问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 17:15:02