add different classes in a foreach

0

I have this code that fills me with an array which displays two images.

for (img of transactionImages) {
    let image = document.createElement("img");
    //$(image).addClass("box_imgpeque");
    $(image).attr("src", "data:image/jpeg;base64," + img);   
    diImages.append(image);
} 

I need to add a different class to each image.

for (img of transactionImages) {
    let image = document.createElement("img");


    $(image).attr("src", "data:image/jpeg;base64," + img);

    $("#diImages img").addClass("imagen1");

    if($("#diImages img").hasClass("imagen1")){
        $("#diImages img").addClass("imagen2");
    } else {
        $("#diImages img").addClass("imagen1");     
    }
}

Try several things, in the latter what you do adds the classes, but to the first element you add the two

Is there any way in which a for cycle adds a class to each different element?

Thanks

    
asked by LoganFenix 12.06.2018 в 23:45
source

2 answers

1

I solved it in the following way:

async function ShowTransactionImages (transactionImages) {     var number = 0;     diImages.empty ();

for (img of transactionImages) {
    let image = document.createElement("img");


    $(image).attr("src", "data:image/jpeg;base64," + img).addClass("box_imgpeque" + numero).addClass("imageresource" + numero);

    diImages.append(image); 

    numero++;

}


    $(".box_imgpeque0").on("click", function () {

        $('#imagepreview').attr('src', $('.imageresource0').attr('src')); // here asign the image to the modal when the user click the enlarge link
        $('#imagemodal').modal('show'); 
    });

    $(".box_imgpeque1").on("click", function () {

        $('#imagepreview').attr('src', $('.imageresource1').attr('src')); // here asign the image to the modal when the user click the enlarge link
        $('#imagemodal').modal('show');
    });

}

It was necessary to add the attributes in the arrangement so that they were not lost, nor add them double.

$ (image) .attr ("src", "data: image / jpeg; base64," + img) .addClass ("box_imgpeque" + number) .addClass ("imageresource" + number);

Thank you all.

    
answered by 14.06.2018 в 00:41
0

You could use a counter like this:

let x = 1;
for (img of transactionImages) {
  let image = document.createElement("img");

  //$(image).addClass("box_imgpeque");
  $(image).attr("src", "data:image/jpeg;base64," + img);

  $(image).addClass("imagen" + x);
  x++;
}
    
answered by 13.06.2018 в 00:02