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) }
额外注意事项
- 代码开头的多余
}需要删除,否则会触发语法错误,导致整个函数无法正常执行。 showOption函数中的state变量需确保已在全局或函数作用域内定义,否则后续依赖状态判断的选项会出现执行错误。
内容的提问来源于stack exchange,提问作者Jan Drawc
相关产品推荐
相关产品推荐

