[英]Images Change on Button Press Broken
当我单击一个按钮时,我试图让一整页的图像发生变化。 这是我当前的代码。 我现在的问题是我可以很好地更改一个图像,但是当我添加代码来更改第二个图像时,它会阻止第一个图像发生变化,也不会让第二个图像变回其原始图像。
这是我的 JavaScript
//First image
var imageSources = ["origonal-image.jpg","2ndimage.jpg"]
var buttons = document.getElementsByClassName("change-image")[0];
var index = 0;
buttons.addEventListener('click', function() {
if (index === imageSources.length) {
index = 0;
}
document.getElementById("imagechangingid").src = imageSources[index];
index++;
});
//Second image
var imageSources1 = ["origonal-image.jpg","2ndimage.jpg"]
var buttons = document.getElementsByClassName("change-image")[0];
var index = 0;
buttons.addEventListener('click', function() {
if (index === imageSources1.length) {
index = 0;
}
document.getElementById("imagechangingid2").src = imageSources1[index];
index++;
});
这是因为当您编写以下代码两次时,您将覆盖您的第一个事件侦听器。 一个实现(我猜是第二个)将覆盖另一个
buttons.addEventListener('click', function() {}
如果同一个按钮点击应该改变两个图像 - 你应该在同一个事件处理程序中处理它。
var imageSources = ["origonal-image.jpg","2ndimage.jpg"]
var buttons = document.getElementsByClassName("change-image")[0];
var imageSources1 = ["origonal-image.jpg","2ndimage.jpg"]
var buttons = document.getElementsByClassName("change-image")[0];
var index = 0;
var indexOne = 0;
buttons.addEventListener('click', function() {
if (index === imageSources1.length) {
index = 0;
}
document.getElementById("imagechangingid2").src = imageSources1[index];
index++;
if (indexOne === imageSources.length) {
indexOne = 0;
}
document.getElementById("imagechangingid").src = imageSources[indexOne];
indexOne++;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.