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

如何用JavaScript实现点击元素切换显示/隐藏HTML表格与表单

解决下拉菜单切换时表格与表单同时显示的问题

嘿,这个问题很常见——就是切换选项时只处理了显示当前元素,却没把之前展示的元素藏起来,所以才会出现两者同时显示的情况。另外你的代码里还有几个小bug,我一起帮你修正啦!

第一步:修改HTML结构,给容器加ID并设置初始隐藏

我们需要给表格和表单的外层容器加上唯一ID,方便JS精准控制它们的显示/隐藏,同时默认把两者都设为隐藏(你也可以根据需求默认显示其中一个):

<div class="collapse navbar-collapse" id="navbarNavDropdown">
  <ul class="navbar-nav">
    <li class="nav-item dropdown">
      <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
        Dropdown link
      </a>
      <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
        <a class="dropdown-item" href="#" onclick="origin()">Action</a>
        <a class="dropdown-item" href="#" onclick="formOrigin()">Another action</a>
      </div>
      <!-- 表格容器:添加ID,初始隐藏 -->
      <div id="table-container" style="display: none;">
        <table class="table" id="origin-table"></table>
      </div>
      <!-- 表单容器:添加ID,初始隐藏 -->
      <div id="form-container" style="display: none;">
        <form id="origin-form">
          <div class="form-group">
            <label for="name">Name</label>
            <input type="text" class="form-control" id="name" placeholder="Enter name">
          </div>
          <div class="form-group">
            <label for="city">City</label>
            <input type="text" class="form-control" id="city" placeholder="city">
          </div>
          <div class="form-group form-check">
            <input type="checkbox" class="form-check-input" id="add">
            <label class="form-check-label" for="add">Check</label>
          </div>
          <button type="submit" class="btn btn-primary">Submit</button>
        </form>
      </div>
    </li>
  </ul>
</div>

第二步:修正JavaScript代码,添加显示/隐藏逻辑

现在修改JS函数,每次点击选项时先隐藏另一个元素,再显示当前目标元素,同时修复原代码里的拼写错误和元素获取问题:

// 声明全局的XMLHttpRequest对象,避免重复创建
let petition = new XMLHttpRequest();

function origin() {
  // 切换时:显示表格容器,隐藏表单容器
  document.getElementById('table-container').style.display = 'block';
  document.getElementById('form-container').style.display = 'none';

  const url = "http://localhost:8000/api/v1/origin";
  petition.onreadystatechange = ResponseOrigin;
  petition.open("GET", url, true);
  petition.send();
}

function ResponseOrigin() {
  let text = "<tr><th>Identifier</th><th>Name</th><th>Numero</th><th>City</th></tr>";
  if (petition.readyState === 4) {
    if (petition.status === 200) {
      const response = petition.responseText;
      // 保留你处理接口返回的逻辑
      const responseC = response.split("<");
      const responseV = responseC[0];
      const data = JSON.parse(responseV);
      
      for (let i = 0; i < data.length; i++) {
        text += `<tr id="${data[i].id}">
                  <td>${data[i].id}</td>
                  <td>${data[i].name}</td>
                  <td>${data[i].city}</td>
                </tr>`;
      }
      // 将生成的表格内容插入到指定表格中
      document.getElementById('origin-table').innerHTML = text;
    } else {
      alert("Problem with URL");
    }
  }
}

function formOrigin() {
  // 切换时:显示表单容器,隐藏表格容器
  document.getElementById('form-container').style.display = 'block';
  document.getElementById('table-container').style.display = 'none';
}

// 给表单添加提交事件,把原有的POST逻辑移到这里(更符合交互逻辑)
document.getElementById('origin-form').addEventListener('submit', function(e) {
  e.preventDefault(); // 阻止默认表单跳转行为
  
  const url = "http://localhost:8000/api/v1/origin";
  petition.onreadystatechange = responseAddOrigin;
  petition.open("POST", url, true);
  petition.setRequestHeader("Content-Type", "application/json"); // 必须设置请求头,否则后端无法解析JSON
  petition.send(JSON.stringify({
    name: document.getElementById('name').value,
    city: document.getElementById('city').value
  }));
});

function responseAddOrigin() {
  if (petition.readyState === 4) {
    if (petition.status === 200) {
      alert("data recorded correctly");
      // 提交成功后重置表单
      document.getElementById('origin-form').reset();
    } else {
      alert("Problem with URL");
    }
  }
}

关键修改点说明

  • 添加容器ID:给表格和表单的外层div加了table-container和form-container,能精准控制整个区域的显示/隐藏,比单独控制表格或表单更方便。
  • 切换时的互斥逻辑:每个点击函数开头都先处理另一个元素的隐藏,确保同一时间只有一个内容显示。
  • 修复JS错误:
    • 修正了原代码里responser的拼写错误;
    • 把document.formOrigin这种过时的表单获取方式改成了getElementById;
    • 给POST请求添加了Content-Type请求头,否则后端可能无法正确解析JSON数据;
    • 把表单提交逻辑从formOrigin函数移到了表单的submit事件里,符合“点击选项显示表单,提交时才发请求”的交互逻辑。

这样修改后,你点击下拉菜单的两个选项时,就只会显示对应的表格或表单啦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:27:51