简体   繁体   English

Javascript 简单的图片库

[英]Javascript simple image gallery

im trying to make a simple javascript photo gallery, in which u can change the img by 2 buttons, to the previous one and to the next one, there are 9 images and if the 9th image is shown and u press next, it should show the first one img, could anyone help me please?我正在尝试制作一个简单的 javascript 照片库,其中您可以通过 2 个按钮将 img 更改为上一个和下一个,有 9 张图像,如果显示第 9 张图像并且您按下一步,它应该显示第一个img,有人可以帮我吗? My code doesnt work.我的代码不起作用。

HTML: HTML:

<body>
<img src="img (1).jpg" alt="" height="200">
<button id="previous">previous image</button>
<button id="next">next image</button>

JS: JS:

<script>
let counter = 1;
let img = document.querySelector("img");
let changeImg = function (type) {
    if (type == 1) {
        counter++   
    } else {
        counter--
    }
    if (counter <= 0) {
        counter = 9
    }
    img.setAttribute("src", "img ("+counter+").jpeg")
}

let previous = document.getElementById("previous")
let next = document.getElementById("next")

previous.addEventListener("click", chaneImg(1))
next.addEventListener("click", changeImg(2))

thanks谢谢

Your problem is with the way you have added your listeners:您的问题在于您添加听众的方式:

previous.addEventListener("click", changeImg(1))

should be应该

previous.addEventListener("click", (e) => changeImg(1))

The first one calls changeImage on load.第一个在加载时调用 changeImage。

 let counter = 1; let img = document.querySelector("img"); let changeImg = function(type) { if (type == 1) { counter++ } else { counter-- } if (counter <= 0) { counter = 9 } img.setAttribute("src", "img (" + counter + ").jpeg") } let previous = document.getElementById("previous") let next = document.getElementById("next") previous.addEventListener("click", (_e) => changeImg(1)) next.addEventListener("click", (_e) => changeImg(2))
 <body> <img src="https://i.imgur.com/Att5gPe.jpg" alt="" height="200"> <button id="previous">previous image</button> <button id="next">next image</button> </body>

Not tested, but a couple of things I see are:未经测试,但我看到的一些事情是:

typo on this line:这一行的错字:

previous.addEventListener("click", changeImg(1))

chaneImg(1) to changeImg(1) chaneImg(1)changeImg(1)

You also don't have a condition to check the inverse of this:你也没有条件来检查这个的逆:

if (counter <= 0) {
    counter = 9
}

so try adding所以尝试添加

if (counter >= 9) {
    counter = 1
}

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

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