Javascript以粗体显示活动选项卡

Javascript以粗体显示活动选项卡,javascript,html,Javascript,Html,嗨,我想用粗体显示活动选项卡。我想我错过了什么。 下面是我的标签: <div class="nav"> <span id="tab1">tab1</span>| <span id="tab2">tab2</span>| <span id="tab3">tab3 </span> </div> <div id="body"> <p> </p>

嗨,我想用粗体显示活动选项卡。我想我错过了什么。 下面是我的标签:

 <div class="nav">
      <span id="tab1">tab1</span>| <span id="tab2">tab2</span>| <span id="tab3">tab3 </span>
</div>
 <div id="body">
      <p> </p>
 </div>

querySelector
只返回一个元素。您需要
querySelectorAll
。然后,您需要对结果进行循环,以从所有匹配的元素中删除该类:

document.querySelectorAll("span").forEach(e => e.classList.remove('active'));
document.getElementById(“tab1”).onclick=function(){
document.queryselectoral(“span”).forEach(e=>e.classList.remove(“active”));
this.classList.add('active');
document.getElementById(“body”).innerHTML=“hello”;
}
document.getElementById(“tab2”).onclick=function(){
document.queryselectoral(“span”).forEach(e=>e.classList.remove(“active”));
this.classList.add('active');
document.getElementById(“body”).innerHTML=“hello2”;
}
document.getElementById(“tab3”).onclick=function(){
document.queryselectoral(“span”).forEach(e=>e.classList.remove(“active”));
this.classList.add('active');
document.getElementById(“body”).innerHTML=“hello3”;
}
.active{
字号:700;
}

表1 |表2 |表3


如果您只有3个选项卡,或者选项卡的数量不太多,则可以使用此脚本对它们进行硬编码。但是如果您有许多选项卡,那么您可以使用j08691建议的解决方案

document.getElementById("tab1").onclick = function () 
{
    document.getElementById("tab1").classList.add('active'); 
    document.getElementById("tab2").classList.remove('active');
    document.getElementById("tab3").classList.remove('active');
    document.getElementById("body").innerHTML =  "hello";
}

document.getElementById("tab2").onclick = function () 
{
    document.querySelector("span").classList.remove('active');
    document.getElementById("tab1").classList.remove('active');
    document.getElementById("tab2").classList.add('active'); 
    document.getElementById("tab3").classList.remove('active');
    document.getElementById("body").innerHTML =  "hello2";
}


document.getElementById("tab3").onclick = function () 
{
    document.querySelector("span").classList.remove('active');
    document.getElementById("tab1").classList.remove('active');
    document.getElementById("tab2").classList.remove('active');
    document.getElementById("tab3").classList.add('active'); 
    document.getElementById("body").innerHTML =  "hello3";
}
希望有帮助…干杯