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

如何消除在线测验页面的undefined文本?JS故障排查求助

问题原因

页面出现undefined的核心原因是:HTML里包含了5个选项(data-number从1到5),但所有题目对象仅定义了choice1到choice4,不存在choice5属性。当JavaScript遍历所有选项时,第5个选项会尝试读取不存在的currentQuestion['choice5'],最终将undefined渲染到页面上。

解决方案

你可以任选一种方式修复:

方式1:移除多余的选项容器(推荐)

直接删除HTML中第5个choice-container,因为所有题目都是4个选项,不需要额外的容器:

<!-- 删除这段多余的代码 -->
<div class="choice-container">
    <p class="choice-text" data-number="5">choice 5</p>
</div>

方式2:保留容器但处理空选项

如果需要保留5个容器的结构,修改JavaScript中设置选项文本的逻辑,当对应选项不存在时隐藏容器或清空文本:

choices.forEach( choice =>{
    const number = choice.dataset['number'];
    const choiceContent = currentQuestion['choice' + number];
    if (choiceContent) {
        choice.innerText = choiceContent;
        choice.parentElement.style.display = 'block';
    } else {
        choice.innerText = '';
        choice.parentElement.style.display = 'none';
    }
})
验证效果

修改完成后刷新页面,undefined文本会消失,其余测验功能可正常运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 15:45:39