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

HTML&JS问卷无法实现答后隐藏当前题显示下一题的问题求助

问题原因及修复方案

核心错误点

  • 参数传递错误:你在onclick里直接写myDIV、subDIV1这类标识符,浏览器会把它们当成未定义的变量,而getElementById需要的是字符串格式的ID,因此根本找不到对应元素。
  • 未定义函数:HTML里用了myFunction2,但JS里只实现了myFunction,子按钮点击会直接报错。
  • 冗余全局变量:hide和show全局变量完全没必要,直接用函数参数更安全,还能避免全局污染。

修正后的代码

JavaScript 部分

function toggleSection(currentId, nextId) {
  // 获取当前要隐藏的元素和要显示的元素
  const currentSection = document.getElementById(currentId);
  const nextSection = document.getElementById(nextId);
  
  // 加判断避免元素不存在时报错
  if (currentSection && nextSection) {
    currentSection.style.display = "none";
    nextSection.style.display = "block";
  }
}

HTML 部分

<div id="myDIV">
  <button onclick="toggleSection('myDIV', 'subDIV1')">Click Me 1</button>
  <button onclick="toggleSection('myDIV', 'subDIV2')">Click Me 2</button>
  <button onclick="toggleSection('myDIV', 'subDIV3')">Click Me 3</button>
  This is my DIV element.
</div>

<div id="subDIV1" style="display: none;">
  <button onclick="toggleSection('subDIV1', 'somethingElse1')">Now Me 1</button>
  <button onclick="toggleSection('subDIV1', 'somethingElse2')">Now Me 2</button>
  <button onclick="toggleSection('subDIV1', 'somethingElse3')">Now Me 3</button>
</div>

<div id="subDIV2" style="display: none;">
  <button onclick="toggleSection('subDIV2', 'somethingElse4')">Now Me 1</button>
  <button onclick="toggleSection('subDIV2', 'somethingElse5')">Now Me 2</button>
  <button onclick="toggleSection('subDIV2', 'somethingElse6')">Now Me 3</button>
</div>

<div id="subDIV3" style="display: none;">
  <button onclick="toggleSection('subDIV3', 'somethingElse7')">Now Me 1</button>
  <button onclick="toggleSection('subDIV3', 'somethingElse8')">Now Me 2</button>
  <button onclick="toggleSection('subDIV3', 'somethingElse9')">Now Me 3</button>
</div>

<!-- 记得补充后续的目标DIV,示例: -->
<div id="somethingElse1" style="display: none;">这是后续问题区块1</div>
<div id="somethingElse2" style="display: none;">这是后续问题区块2</div>
<!-- 其他目标区块同理补充 -->

额外优化建议

  • 给所有问卷区块加统一类名(比如question-block),用CSS批量设置默认隐藏样式,避免重复写style="display: none;":
.question-block {
  display: none;
}
/* 默认显示第一个区块 */
#myDIV {
  display: block;
}
  • 避免内联onclick,改用事件委托绑定点击事件,代码更整洁易维护:
document.addEventListener('DOMContentLoaded', function() {
  document.body.addEventListener('click', function(e) {
    if (e.target.tagName === 'BUTTON') {
      const currentId = e.target.dataset.current;
      const nextId = e.target.dataset.next;
      if (currentId && nextId) {
        toggleSection(currentId, nextId);
      }
    }
  });
});

对应的HTML按钮改成:

<button data-current="myDIV" data-next="subDIV1">Click Me 1</button>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 07:54:56