Appended image tag with src path from JSON file is displaying incorrectly. As seen in the console, to the div
tag it is appended:
<div id="photoContainer" ></div>
"<img src=photos/43432424.jpg id=img1>" ( just string with "" )
"<img src=photos/43432424.jpg id=img1>"
"<img src=photos/43432424.jpg id=img1>"
image can be seen here: https://jefrey12212445.imgur.com/all/
<div id="photoContainer"></div>
` <script>
let photoContainer = $('#photoContainer');
function renderImages(data) {
data.forEach(function (item) {
photoContainer.append(`<img id=${item.id} src=${item.location}>`);
})
};`
`$.getJSON("/json/photos.json", function (data) {
renderImages(data);
});`
I want all the images from the JSON file be displayed as a gallery.
Currently, you append a plain js string into the dom. To create a new element in jquery, you can use eg $("<div />")
.
For more information please have a look here
let photoContainer = $('#photoContainer'); const renderImages = data => data.forEach(item => { const newEle = $(`<img id=${item.id} src=${item.location} />`) photoContainer.append(newEle); }) //$.getJSON("/json/photos.json", renderImages); // Fake API const fakeGetImage = (_, callback) => callback([ { id: "pic1", location: "https://picsum.photos/id/766/200/200" } ]) fakeGetImage("url", renderImages)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="photoContainer"></div>
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.