首页 > 解决方案 > 如何在 HTML/JavaScript 中动态添加选项卡?

问题描述

当谈到这个 HTML 东西时,我是个新手,所以我不知道如何让它工作。我一直在关注这个标签的描述https://www.w3schools.com/howto/howto_js_tabs.asp

我会定期发送 GET 请求并接收字符串 ID,因此我想为收到的每个唯一 ID 创建一个选项卡,但我不确定如何执行此操作。

<div class="tab">
  <button class="tablinks" onclick="openCity(event, 'London')" id="defaultOpen">SOAP5</button>
  <button class="tablinks" onclick="openCity(event, 'Paris')">GDAL</button>
  <button class="tablinks" onclick="openCity(event, 'Tokyo')">IDK</button>
</div>

<div id="London" class="tabcontent" style="height:100%;">
  <!--#include virtual='navigation.htm' -->
</div>

<div id="Paris" class="tabcontent" style="height:100%;">
  <!--#include virtual='navigation.htm' -->
</div>

<div id="Tokyo" class="tabcontent" style="height:100%;">
  <!--#include virtual='navigation.htm' -->
</div>

<script>
function openCity(evt, cityName) {
  var i, tabcontent, tablinks;
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }
  document.getElementById(cityName).style.display = "block";
  evt.currentTarget.className += " active";
}

// Get the element with id="defaultOpen" and click on it
document.getElementById("defaultOpen").click();
</script>

function RefreshData() {
  var xmlhttp = new XMLHttpRequest();
  // Periodic data request
  var intervalID = setInterval(function GetData() {
    xmlhttp.open('GET', 'formInfo.htm', true);
    if ((xmlhttp.readyState = xmlhttp.OPENED)) {
      xmlhttp.send();
    }
  }, 1000);

  xmlhttp.onreadystatechange = function () {
    if (this.readyState === this.DONE) {
      UpdateTabs(xmlhttp);
    }
  };
}

function UpdateTabs(xmlhttp) {
  //How to create new tabs here?
}

标签: javascripthtmltabs

解决方案


推荐阅读