简体   繁体   English

通过单击按钮更改 javascript 中的 img src

[英]changing img src in javascript by click on button

this is my code: I want to change the img src by clicking on the button and add one to the counter that change the next photo again But only the first photo is displayed: and I have 8 img in this path;这是我的代码:我想通过单击按钮更改 img src 并将一个添加到再次更改下一张照片的计数器但只显示第一张照片:并且我在此路径中有 8 个 img; images/slides/writing${0-7};图片/幻灯片/写作${0-7};

 slider = () =>{ let i=0; let slides = document.getElementById('slides').getElementsByTagName('img')[0]; slides.src = `images/slides/writing${i}.jpg`; i++ }
 <section id="slides"> <picture> <img src="" alt="Slide img"> <input type="button" value="change" onclick="slider()"> </picture> </section>

You are always setting i to 0 inside the function, just make it global and make sure it doesn't exceed 7 :您总是在 function 中将i设置为 0,只需将其设为全局并确保它不超过7

let i=0;
slider = () =>{
    if(i==8) i=0;
    let slides = document.getElementById('slides').getElementsByTagName('img')[0];
    slides.src = `images/slides/writing${i}.jpg` ; 
    i++
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM