javascript - 按钮按下时图像更改损坏
问题描述
当我单击一个按钮时,我试图让一整页的图像发生变化。这是我当前的代码。我现在的问题是我可以很好地更改一个图像,但是当我添加代码来更改第二个图像时,它会阻止第一个图像发生变化,也不会让第二个图像变回其原始图像。
这是我的 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++;
});
推荐阅读
- java - 执行使用 RestTemplate 返回列表的 POST 请求时出错
- pandas - 您可以让 CloudWatch 指标筛选器查看模式在单个事件中显示的次数吗?
- dictionary - 通过指针的指针更新结构不起作用
- django - websocket因“无效的帧头”而失败
- camera - 使用 ZXing for javascript form camera 检测多个 QR 码
- c# - 使用 Linq 时出现 Stackoverflow 异常
- visual-studio-code - 如何将 VSCode 连接到 GCP 实例
- slack - 在 Slack API 上定位机器人用户名
- javascript - GAS:从电子表格数据填充下拉列表
- css - 带有 React 样式组件的伪元素