简体   繁体   中英

displaying image from image array not working

The following code i have below tries to display images from an image array but fail to display in ul of html tag.

it uses javascript to set width and height of image. and jquery to call display all image function.

how to correct it to display image from image from image array?

 var backgroundImage = new Array(); backgroundImage[0] = "https://picsum.photos/200/300/?random"; backgroundImage[1] = "https://picsum.photos/200/300/?random"; backgroundImage[2] = "https://picsum.photos/200/300/?random"; backgroundImage[3] = "https://picsum.photos/200/300/?random"; backgroundImage[4] = "https://picsum.photos/200/300/?random"; backgroundImage[5] = "https://picsum.photos/200/300/?random"; backgroundImage[6] = "https://picsum.photos/200/300/?random"; function displayAllImages() { var i = 0, len = backgroundImage.length; for (; i < backgroundImage.length; i++) { var img = new Image(); img.url = backgroundImage[i]; img.style.width = '200px'; img.style.height = '200px'; document.getElementById('images').appendChild(img); } }; $(function() { displayAllImages(); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="container"> <div class="backgoundImage"> <ul id="images"></ul> </div> </div>

Should be img.src instead of img.url .

 var backgroundImage = new Array(); //Use a loop instead // backgroundImage[0] = "https://picsum.photos/200/300/?random"; // backgroundImage[1] = "https://picsum.photos/200/300/?random"; // backgroundImage[2] = "https://picsum.photos/200/300/?random"; // backgroundImage[3] = "https://picsum.photos/200/300/?random"; // backgroundImage[4] = "https://picsum.photos/200/300/?random"; // backgroundImage[5] = "https://picsum.photos/200/300/?random"; // backgroundImage[6] = "https://picsum.photos/200/300/?random"; //omit the last query param if all images are to be the same for(var j = 0; j <= 6; j++){ backgroundImage[j] = "https://picsum.photos/200/300/?random&img="+j; } function displayAllImages() { var i = 0, len = backgroundImage.length; for (; i < backgroundImage.length; i++) { var img = new Image(); img.src = backgroundImage[i]; img.style.width = '200px'; img.style.height = '200px'; document.getElementById('images').appendChild(img); } }; $(function() { displayAllImages(); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="container"> <div class="backgoundImage"> <ul id="images"></ul> </div> </div>

Check also: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#Image_loading_errors

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