Adrian Cee Adrian Cee - 2 months ago 7
HTML Question

How to add one value of JSON to each div?

how i can to add one element from JSON to each div?
(in each div should be other image)

html

<div class="card"></div>
<div class="card"></div>
<div class="card"></div>


script

var i;
var jsonURL = "img.json";
$.getJSON(jsonURL, function (json){
var img= "";
$.each(json.images, function () {
for(i=1;i<=2;i++){
img += '<img src= "' + this.url + '">';
}
});
$(".card").append(img);
});


json

{ "images": [
{"url": "f1.png"},
{"url": "f2.png"},
{"url": "f3.png"} ]}

Answer

From your question, I assumed that you want to add images, div by div. That can be done by eq() as shown below.

$.each(json.images, function (key, value) {
   $(".card").eq(key).append('<img src= "' + value.url + '">');    
});

var json = { "images": [
{"url": "f1.png"},
{"url": "f2.png"},
{"url": "f3.png"} ]};

$.each(json.images, function (key, value) {
        $(".card")
          .eq(key)
          .append('<img src= "' + value.url + '">');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="card"></div>
<div class="card"></div>
<div class="card"></div>