您好,
任何人都可以告诉我为什么每次我点击黄色按钮控制台日志显示我的值为false? (每次点击后应交替错误,对错等)
哪里出错?
var btn = document.querySelectorAll('.cdi-link');
var dropdown = document.getElementsByClassName('cdi-dropdown')
for (var i = 0; i < btn.length; i++) {
btn[i].addEventListener('click', function() {
var button = this;
var arrow = button.lastElementChild.lastElementChild;
var btnColor = button.lastElementChild;
var flag = true;
if (flag) {
flag = false;
console.log(flag);
} else {
flag = true;
console.log(flag);
}
});
}
<section class="cursos-de-ingles">
<article class="main-cdi">
<div class="cdi cdi-one">
<div class="cdi-header">
<img src="img/numero1.png" alt="">
</div>
<div class="cdi-par">
<button type="button" class="cdi-link">
<div>
<span>Ver detalles de cursos de Inglés General</span> <span class="arrow">▶</span>
</div>
</button>
</div>
<!--cdi-par-->
<img src="img/greybox.png" alt="">
</div>
<!--cdi-one-->
<div class="cdi cdi-two">
<button type="button" class="cdi-link">
<div>
<span>Ver detalles de los cursos de Inglés Académico</span> <span class="arrow">▶</span>
</div>
</button>
</div>
<!--cdi-par-->
<img src="img/greybox.png" alt="">
<!--cdi-two-->
<div class="cdi cdi-three">
<div class="cdi-header">
</div>
<div class="cdi-par">
<button type="button" class="cdi-link">
<div>
<span>Ver detalles de los cursos individuales</span> <span class="arrow">▶</span>
</div>
</button>
</div>
<!--cdi-par-->
<img src="img/greybox.png" alt="">
</div>
<!--cdi-three-->
答案 0 :(得分:1)
这是因为当点击发生时,标志始终设置为true,因此它会将自身设置为false。标志的声明应移到click处理程序之外。
答案 1 :(得分:1)
将您的标志移到eventListener之外并进行循环,因为在每次单击或循环时,您都会将标志设置为true。
var btn = document.querySelectorAll('.cdi-link');
var dropdown = document.getElementsByClassName('cdi-dropdown')
var flag = true;
for (var i = 0; i < btn.length; i++) {
btn[i].addEventListener('click', function() {
var button = this;
var arrow = button.lastElementChild.lastElementChild;
var btnColor = button.lastElementChild;
if (flag) {
flag = false;
console.log(flag);
} else {
flag = true;
console.log(flag);
}
});
}
但如果您想为不同的点击设置不同的标记,请改为使用地图:
var btn = document.querySelectorAll('.cdi-link');
var dropdown = document.getElementsByClassName('cdi-dropdown')
var flags = {};
for (var i = 0; i < btn.length; i++) {
btn[i].addEventListener('click', function() {
var button = this;
var arrow = button.lastElementChild.lastElementChild;
var btnColor = button.lastElementChild;
if (flag[i]) {
flag[i] = false;
console.log(flag[i]);
} else {
flag[i] = true;
console.log(flag[i]);
}
});
}