如何使用javascript获取激活的选项卡名称

时间:2018-05-24 07:44:57

标签: javascript html css3

我有一个像导航栏这样的标签如果我点击选项卡,标签内容将会改变我想要获取激活标签的标签名称怎么办。 这是代码。 HTML:

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

<div id="London" class="tabcontent">
  <h3>London</h3>
  <p>London is the capital city of England.</p>
</div>

<div id="Paris" class="tabcontent">
  <h3>Paris</h3>
  <p>Paris is the capital of France.</p> 
</div>

<div id="Tokyo" class="tabcontent">
  <h3>Tokyo</h3>
  <p>Tokyo is the capital of Japan.</p>
</div>

脚本:

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";
}

这里是参考enter link description here

1 个答案:

答案 0 :(得分:1)

var activeTabname = "";

function openCity(evt, cityName) {
    activeTabname = cityName;
    ...
    ...
 }

在您需要的时候使用activeTabname

通过查看课程.active

找到有效标签
var activeTab = document.querySelector(".tabcontent.active");