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

如何在函数内添加事件监听器实现分类随机选词功能

点击分类按钮随机选取对应单词的实现方案

问题根源

你错误地将DOM容器元素wordCategoriesButton赋值给了wordArray,但DOM元素并非单词数组,因此无法通过索引获取随机元素。

修正后的完整代码

// 单词分类数据
const words = {
    arm: ['humerus', 'ulna', 'radius'],
    leg: ['femur', 'tibia', 'fibula'],
    skull: ['frontal', 'occipital', 'temporal'],
}

// 缓存分类容器元素
const wordCategoriesContainer = document.getElementById('words-container');

// 点击事件监听器
wordCategoriesContainer.addEventListener('click', function (event) {
    // 获取点击的分类名称,去除首尾空格避免匹配错误
    const category = event.target.textContent.trim();
    
    // 验证分类是否存在于单词数据中
    if (words[category]) {
        // 获取对应分类的单词数组
        const wordArray = words[category];
        // 随机选取一个单词
        const secretWord = wordArray[Math.floor(Math.random() * wordArray.length)];
        
        console.log('选中分类:', category);
        console.log('随机单词:', secretWord);
    } else {
        console.log('无效分类,请点击正确的分类按钮');
    }
})

关键细节说明

  • 属性访问方式:使用words[category]而非words.category,因为category是动态变量,方括号语法才能正确访问对象的对应属性。
  • 文本处理:添加trim()处理按钮文本,避免因按钮内的空格导致分类名称不匹配。
  • 容错处理:增加if (words[category])判断,防止点击容器内非按钮元素时出现报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 11:07:44