首页 > 解决方案 > 每次单击按钮时用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);
}


})

标签: javascripthtml

解决方案


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
  }
});

推荐阅读