我已经建立了一个标签栏网站,它只使用一个页面我使用js隐藏3个元素并显示一个。当我点击链接显示一个并隐藏其他链接时,所有内容都会混乱,显示3个或2个随机。这是我的代码。
function unhide(divID, otherDivId, otherDivId, otherDivId) {
var item = document.getElementById(divID);
if (item) {
item.className = (item.className == 'hidden') ? 'unhidden' : 'hidden';
}
document.getElementById(otherDivId).className = 'hidden';
}

.hidden {
display: none;
}
.unhidden {
display: block;
}

<div id="tweaked" class="hidden">
<p>Test1</p>
<footer class="bottom">
<a class="tab current" href="javascript:unhide('home', 'tweaked', 'other', 'more')">Home<i class="material-icons">home</i></a>
<a class="tab" href="javascript:unhide('tweaked', 'home', 'other', 'more')">Tweaks<i class="material-icons">view_headline</i></a>
<a class="tab" href="javascript:unhide('other', 'home', 'tweaked', 'more')">Other<i class="material-icons">view_headline</i></a>
<a class="tab" href="javascript:unhide('more', 'tweaked', 'other', 'more')">More<i class="material-icons">share</i></a>
</footer>
</div>
&#13;
答案 0 :(得分:1)
也许你想要这样的东西:
var anchors = document.querySelectorAll(".bottom .tab"),
showHide = function(e) {
var parent = this.parentNode;
anchors.forEach(a => {
var relatedDiv = document.getElementById(a.dataset.tab),
aClass = a.className.trim();
if (a.dataset.tab != this.dataset.tab) {
relatedDiv.className = relatedDiv.className.replace("unhidden", "") + " hidden";
a.className = aClass.replace("current", "");
} else {
relatedDiv.className = relatedDiv.className.replace("hidden", "") + " unhidden";
a.className = aClass.replace("current", "") + " current";
}
});
};
anchors.forEach(a => a.addEventListener("click", showHide));
.hidden{
display:none;
}
.unhidden{
display:block;
}
<div id="home" class="unhidden">
<p>Home</p>
</div>
<div id="tweaked" class="hidden">
<p>Tweaks</p>
</div>
<div id="other" class="hidden">
<p>Other</p>
</div>
<div id="more" class="hidden">
<p>More</p>
</div>
<footer class="bottom">
<a class="tab current" href="#" data-tab="home">Home<i class="material-icons">home</i></a>
<a class="tab" href="#" data-tab="tweaked">Tweaks<i class="material-icons">view_headline</i></a>
<a class="tab" href="#" data-tab="other">Other<i class="material-icons">view_headline</i></a>
<a class="tab" href="#" data-tab="more">More<i class="material-icons">share</i></a>
</footer>
答案 1 :(得分:0)
你试过item.classList
吗?
Element.classList | MDN
您可以尝试这样的事情:
if(item.classList.contains("hidden")){
item.classList.remove("hidden");
item.classList.add("unhidden");
}else{
item.classList.add("hidden");
item.classList.remove("unhidden");
}