javascript - 每次单击按钮时用JS更改图像
问题描述
我正在尝试执行以下操作:每次单击“下一步”按钮时更改图像。现在,book
在我单击next
一次按钮后,代码为我提供了数组中的最后一张图像。有没有办法可以做到?
HTML 代码:
<body>
<div class="main_page">
<button type="button" id="start">Start</button>
<button type="button" id="next">Next</button>
</div>
</body>
JS代码:
document.addEventListener('DOMContentLoaded', () => {
let book = [
{
name: 'page1',
img: 'img/page1.png'
},
{
name: 'page2',
img: 'img/page2.png'
},
{
name: 'page3',
img: 'img/page3.png'
}
]
const main_page = document.querySelector('.main_page');// with this variable I have conttrol of
// div with class .main_page
let mainImg = document.createElement('img') // similar to HTML tag <img>. this var-ble creates <img> tag in HTML Document
mainImg.setAttribute('src', book[0].img) // making attribute to <img> tag through JavaScript
main_page.appendChild(mainImg);// appending <img> tag to the div with class main_page
let next = document.getElementById('next');
const turnPage = (count) =>{
//if(mainImg.getAttribute("src") == 'img/page2.png') alert("hey")//mainImg.src = {firstpage}
next.addEventListener('click', () => {
if(mainImg.getAttribute("src") == book[count].img){
//alert("hey")
mainImg.src = book[count+1].img
}})
}
for(let i = 0; i< book.length; i++){
turnPage(i);
}
})
解决方案
Teemu 在评论中说的是对的。由于我的声誉很低,我无法发表评论。所以在这里提供代码。只需删除 turnPage 函数定义和 for 循环。并用下面的代码替换它。
let count = 0, len = book.length;
next.addEventListener('click', () => {
if(mainImg.getAttribute("src") == book[count].img){
count = (count + 1) % len;
mainImg.src = book[count].img
}
});
推荐阅读
- javascript - 在 React 中,如果状态不影响渲染,是否可以在 setState 之后跳过重新渲染?
- ruby - PG::ConnectionBad:无法将主机名“postgres”转换为地址:没有与主机名关联的地址
- c# - 如何单击子窗体上的十字按钮(取消按钮)并转到主窗体?
- c - 使用 Makefile 编译任何单个 C 代码
- c - C 新手尝试进行循环。Realloc():无效的下一个大小问题
- ios - Swift-调整约束以允许键盘
- flutter - formdata在颤动中转换为字符串
- python - 如何遍历文件的每一行并打印出任何包含两个相邻元音的单词?
- html - 有没有办法让这个 H1 在 div 的底部居中?
- python - 使用 Python 删除 Gmail 中的特定电子邮件