简体   繁体   中英

Displaying Images from a Javascript Array

I am creating a JS snippet to display an overlay on a webpage and need to scrape the images, save them to a variable, and display them on a overlay.

I currently have the images I need in an array:

var itemImages = $(".itemImg img");
var imageArray = [];
for (i = 0; i < itemImages.length; i++) {
  imageArray.push("<li><img src='" + itemImages[i].src + "'/></li>");
}

The image array looks like this:

["<li><img src='http://cdnmedia.marmot.com/images/product/tile/75940_9149_f.jpg'/></li>", "<li><img src='http://cdnmedia.marmot.com/images/product/tile/18840_001_f.jpg'/></li>"]

I can seem to figure out how to display these in my code. The function currently looks like this:

function displayModal(itemCount, imageArray, cartTotal) {
  $("<article id='modal'><div id='itemCount'>" + "Total Items: " 
    + itemCount + "<br><div id=itemImages>" + "<div id='images'>" + "IMAGES!" +
    "</div></div></div></article>").css({
    "width": "461px",
    "height": "263px",
    "line-height": "200px",
    "position": "fixed",
    "top": "50%",
    "left": "50%",
    "margin-top": "-155px",
    "margin-left": "-232px",
    "background-color": "rgb(255,255,255)",
    "border-radius": "5px",
    "text-align": "center",
    "z-index": 101,
    "border": "1px solid rgb(227,227,227)",
    "border-top": "4px solid rgb(217,0,31)"
  }).appendTo("#overlay");
  $("#itemCount").css({
    "position": "relative",
    "bottom": "79px",
    "font-family": "Helvetica",
    "color": "#000",
    "font-size": "16px"
  }).appendTo("#modal");
}

I'm using the place-holding IMAGES! for the actual images. I can't seem to display the images themselves, only the word "object".

I suspect that this is because you're referencing the imageArray array - which is an object - but what you want are the elements within the array.

You can retrieve the individual items in the array in a similar way to how you first added them, eg

    for (i = 0; i < imageArray.length; i++) {
      var image = imageArray[i];
    } 

Or you could build up a string of all your image HTML by adding the following to the beginning of your displayModal function:

    var imageHTML = "";
    for (i = 0; i < imageArray.length; i++) {
      imageHTML += imageArray[i];
    } 

and adding imageHTML into your generated HTML in place of "IMAGES!"

I've added a working example to JSFiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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