Slider FileReader JS Multiple Image Upload (Incrementing Index)

后端 未结 2 1836
盖世英雄少女心
盖世英雄少女心 2020-12-10 16:40

I am trying to make a JavaScript multiple image uploader that uploads image previews to a slider, but I am having some issues. So far it looks like I was able to get the ima

2条回答
  •  独厮守ぢ
    2020-12-10 17:16

    The problem with the code is that by the time the load event executes - the for loop has already incremented. So if two images are added - the value of i when the load event is executing is already 2.

    One way to solve this is to add the value of i to an array and retrieve it in the event listener one by one:

    var arrFilesCount = [];
    
    for (var i = 0; i < files.length; i++) {
         arrFilesCount.push(i);   //push to array
    
         var file = files[i];
    
         //Only pics
         if (!file.type.match('image')) continue;
    
            var picReader = new FileReader();
            picReader.addEventListener("load", function (event) {
            var picFile = event.target;
    
            current_i = arrFilesCount.shift(); // get from array instead of using i
            prev_i = current_i - 1;
            next_i = current_i + 1;
            ...
            ...
    

    Corresponding jsFiddle here


    Now, this array can also be used for determining the first/last element and thereby using this to go from last to first element. Because we cannot be sure when the event listener will execute (say if there are 100 images the first event listener may execute when the count of loop has reached 5 or 10), so I've used two loops instead of one. The first loop just to populate the array.

    var arrFilesCount = [];
    for (var i = 0; i < files.length; i++) {
         arrFilesCount.push(i);
    }
    

    Lets use this to find the first and last elements

    current_i = arrFilesCount.shift();
    if(current_i === 0){
        prev_i = files.length - 1;   //This is for the first element. The previous slide will be the last image. (i=length-1)
    }
    else{
        prev_i = current_i - 1;
    }
    if(arrFilesCount.length === 0){
        next_i = 0;     //This is for the last element. The next slide will be the first image (i=0)
    }
    else{
        next_i = current_i + 1;
    }
    

    See this jsFiddle.


    Finally, there can be scenarios where the user first adds a couple of images then clicks on upload button again and adds a couple of more images. In this case we need to correct the existing href. The elements which we need to correct are the next of last and prev of first. This can be done using:

    var start = $(output).find('li').length;
    var end = start+ files.length;
    
    if(start !== 0){
        $(output).find('li > nav > a.prev').first().attr('href','#slide-' + (end-1));
        $(output).find('li > nav > a.next').last().attr('href','#slide-'+start);
    }
    

    So the final jsFiddle will be something like this.

提交回复
热议问题