我试图在javascript中创建一组按钮,这些按钮使滑块根据我单击的按钮交换图像。
我想出了这个丑陋的冗余代码:
var changer1 = document.getElementById("changer1");
var changer2 = document.getElementById("changer2");
var changer3 = document.getElementById("changer3");
var r = document.getElementsByClassName('carousel-item');
changer1.addEventListener('click', function() {
for (let i = 0; i < r.length; i++) {
r[i].classList.remove('active')
}
r[0].classList.add('active')
});
changer2.addEventListener('click', function() {
for (let i = 0; i < r.length; i++) {
r[i].classList.remove('active')
}
r[1].classList.add('active')
});
changer3.addEventListener('click', function() {
for (let i = 0; i < r.length; i++) {
r[i].classList.remove('active')
}
r[2].classList.add('active')
});
它确实有效,但是我知道可以优化冗余代码,所以我尝试了这一点:
var changersArray = document.getElementsByClassName('changers');
for (let i = 0; i < 3; i++) {
changer[i].addEventListener('click', function() {
for (let i = 0; i < r.length; i++) {
r[i].classList.remove('active')
}
r[0].classList.add('active')
});
}
这是HTML:
<section class="container-fluid sectionFive">
<div class="row title_image">
<div class="col-sm-12">
<h1 class="wow flipInY delay-1s slow">Testimonials</h1>
</div>
</div>
<div class="row">
<div class="col-sm-2"></div>
<div class="col-sm-8 fetchDiv">
<div id="carouselExampleControls" class="carousel slide wow
fadeIn" data-ride="carousel">
<div class="carousel-inner">
<div class="carousel-item active">
<img class="mt-2 rounded-circle people" src="images/person_3.jpg" alt="">
<p class="frase"></p>
<p class="author"></p>
</div>
<div class="carousel-item">
<img class="mt-2 rounded-circle people" src="images/person_2.jpg" alt="">
<p class="frase"></p>
<p class="author"></p>
</div>
<div class="carousel-item">
<img class="mt-2 rounded-circle people" src="images/person_1.jpg" alt="">
<p class="frase"></p>
<p class="author"></p>
</div>
</div>
<a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#carouselExampleControls" role="button" data-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
</div>
<div class="col-sm-2">
</div>
</div>
<div class="row changersRow">
<button class="changers" id="changer1">1</button><button class="changers" id="changer2">2</button><button class="changers" id="changer3">3</button>
</div>
</section>
我试图通过在循环内写入changer [i]来动态创建changer1,changer2和changer3,但是没有用。
请,您能帮我弄清楚为什么它不起作用以及如何使它起作用吗?
谢谢。
答案 0 :(得分:2)
头两个方面的改进来自我的头脑:
for (let i = 0; i < 3; i++) {
changer[i].addEventListener('click', function() {
for (let j = 0; j < r.length; j++) {
r[j].classList.remove('active')
}
r[i].classList.add('active')
});
}
请注意,内部i
已被替换,r[0]
已更改为使用实际索引