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

HTML文档中按钮创建失败问题排查求助

问题排查:文本冒险游戏按钮无法创建

核心错误:数组遍历方法拼写错误

你的代码里存在一个关键语法错误:textNode.options.foreach应改为textNode.options.forEach(注意大写的E)。JavaScript中数组的遍历方法标准写法是forEach(),小写的foreach不是合法方法,这会导致循环代码完全不执行,自然无法创建任何按钮。

修复后的代码片段

function ShowTextNode(textNodeIndex) {
    const textNode = textNodes.find(textNode => textNode.id === textNodeIndex)
    textElement.innerText = textNode.text
    while (optionButtonsElement.firstChild) {
        optionButtonsElement.removeChild(optionButtonsElement.firstChild)
    }

    // 修正拼写:foreach → forEach
    textNode.options.forEach(option => {
        if (showOption(option)) {
            const button = document.createElement('button')
            button.innerText = option.text
            button.classList.add('btn')
            button.addEventListener('click', () => SelectOption(option))
            optionButtonsElement.appendChild(button)
        }
    })
}

function showOption(option) {
    return option.requiredState == null || option.requiredState(state)
}

额外注意事项

  1. 代码开头的多余}需要删除,否则会触发语法错误,导致整个函数无法正常执行。
  2. showOption函数中的state变量需确保已在全局或函数作用域内定义,否则后续依赖状态判断的选项会出现执行错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 02:57:38