简体   繁体   English

JavaScript:将 for 循环与单击处理程序事件结合使用。 循环跳到最后一项

[英]JavaScript: using a for loop in combination with a click handler event. The loop skips to the last item

I'm learning JavaScript and am trying to use a create a picture carousel.我正在学习 JavaScript 并尝试使用创建图片轮播。 I have a button attached to a click handler event and a for loop to insert an image into an empty HTML IMG element.我有一个附加到单击处理程序事件的按钮和一个用于将图像插入空 HTML IMG 元素的 for 循环。 The images and alt values are sorted in an object containing an image and alt array.图像和 alt 值在包含图像和 alt 数组的 object 中排序。 Instead of moving one image at a time with each click, it skips straight to the last item?不是每次点击一次移动一个图像,而是直接跳到最后一项? can anyone help me with where I'm going wrong?谁能帮我解决我哪里出错了?


const images = {  
    
   image: ["images/alice.jpg", "images/basketball.JPG", "images/butterfly.JPG", "images/colour.JPG", "images/david.JPG", "images/dope.JPG", "images/fire.JPG", "images/friday.JPG", "images/link.jpg", "images/lion.jpg", "images/rose.JPG", "images/skull.JPG"  ],
    alt: ["alice in wonderland", "basketball", "bufferfly and skull", "colour", "david attenbourgh", "dope", "fire", "friday the 13th", "link", "lion", "rose", "skull"]

};

const back = document.getElementById("back");
const next = document.getElementById("next");
const image = document.getElementById("image");

image.setAttribute("src", images.image[0]);
image.setAttribute("alt", images.alt[0]);

next.addEventListener("click", () => {

   for ( let i = 0; i < images.image.length; i++ ) {
        image.setAttribute("src", images.image[i]);
         
    }
    for ( let i = 0; i < images.alt.length; i++ ) {
        image.setAttribute("alt", images.alt[i]); 
    }
});

OK, brother. OK哥。

I think that is because you are new to program?我认为那是因为您是编程新手?

The function you add on click event is not running as expected, because it actually sets image attribute from 0, 1, ..., images.length - 1 but not change one by one when you click.您在单击事件时添加的 function 未按预期运行,因为它实际上将图像属性设置为 0, 1, ..., images.length - 1 但单击时不会一一更改。

So, what you really need to do is that correct the function on 'click' event and make it changes one by one as you click.所以,你真正需要做的是更正'click'事件上的function,并让它在你点击时一一改变。

I think closure will help you, or you can simply use a global variable to record the current image index.我认为闭包会对您有所帮助,或者您可以简单地使用全局变量来记录当前图像索引。

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

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