我在JS上创建了选项卡,而我的脚本决定拒绝工作。 我单击选项卡-它们不起作用,内容也没有隐藏。 Chrome没有显示错误。代码应该毫无疑问地工作,但是似乎有些错误。所有的类,例如“隐藏”,“显示”都是在外部style.css文件上创建的。 请帮忙!!
var tab;
var content;
window.onload = function() {
content = document.querySelector('.content');
tab = document.querySelector('.tab');
hideTabsContent(1);
}
function hideTabsContent(a) {
for (var i = a; i < content.length; i++) {
content[i].classList.remove('show');
content[i].classList.add("hide");
tab[i].classList.remove('active');
}
}
document.querySelector('.container').onclick = function(event) {
var target = event.target;
if (target.className == 'tab') {
for (var i = 0; i < tab.length; i++) {
if (target == tab[i]) {
showTabsContent(i);
break;
}
}
}
}
function showTabsContent(b) {
if (content[b].classList.contains('hide')) {
hideTabsContent(0);
tab[b].classList.add('active');
content[b].classList.remove('hide');
content[b].classList.add('show');
}
}
.tab {
cursor: pointer;
}
.active {
color: white;
background-color: green;
}
.show {
display: block;
}
.hide {
display: none;
}
<div class="container">
<div class="tab active">Summer</div>
<div class="tab">Autumn</div>
<div class="tab">Winter</div>
<div class="content">
<img src="img/pic-1.jpg">
<img src="img/pic-2.jpg">
<img src="img/pic-3.jpg">
</div>
<div class="content">
<img src="img/pic-4.jpg">
<img src="img/pic-5.jpg">
<img src="img/pic-6.jpg">
</div>
<div class="content">
<img src="img/pic-7.jpg">
<img src="img/pic-8.jpg">
<img src="img/pic-9.jpg">
</div>
</div>
答案 0 :(得分:1)
使用querySelectorAll返回元素数组,或者仅返回找到的第一个元素。
window.onload=function() {
content=document.querySelectorAll('.content');
tab=document.querySelectorAll('.tab');
hideTabsContent(1);
}
答案 1 :(得分:1)
下面将选择从querySelctor()
更改为querySelectorAll()
的工作示例
var tab;
var content;
window.onload = function() {
content = document.querySelectorAll('.content');
tab = document.querySelectorAll('.tab');
hideTabsContent(1);
}
function hideTabsContent(a) {
for (var i = a; i < content.length; i++) {
content[i].classList.remove('show');
content[i].classList.add("hide");
tab[i].classList.remove('active');
}
}
document.querySelector('.container').onclick = function(event) {
var target = event.target;
if (target.className == 'tab') {
for (var i = 0; i < tab.length; i++) {
if (target == tab[i]) {
showTabsContent(i);
break;
}
}
}
}
function showTabsContent(b) {
if (content[b].classList.contains('hide')) {
hideTabsContent(0);
tab[b].classList.add('active');
content[b].classList.remove('hide');
content[b].classList.add('show');
}
}
.tab {
cursor: pointer;
}
.active {
color: white;
background-color: green;
}
.show {
display: block;
}
.hide {
display: none;
}
<div class="container">
<div class="tab active">Summer</div>
<div class="tab">Autumn</div>
<div class="tab">Winter</div>
<div class="content">
<span>1</span>
<span>2</span>
<span>3</span>
</div>
<div class="content">
<span>4</span>
<span>5</span>
<span>6</span>
</div>
<div class="content">
<span>7</span>
<span>8</span>
<span>9</span>
</div>
</div>