2

I am working to consume images using a REST call . When I parse one Image , it's working out .

 var img = data.results[0].value; 
 $('#result').html("<img id='img1'>"); $('#img1').attr('src', img);

But when I did loop to get different images , it won't work .

$.each(data.items, function(i,item){
          var img = data.results[i].value; 

         htmlString += '<li><img src=' + img +'/></li>';
});
$('#result').html(htmlString);

Do I have problem with JQuery Loop !

6
  • this is not a loop. you always get same images because data.results[0].value; try results[i]
    – caoglish
    Jul 25, 2013 at 23:59
  • You're setting img to results[0] no matter what, and for some reason using data.items instead of data.results
    – Trojan
    Jul 26, 2013 at 0:00
  • also, base on meaning of the literary, this make no sense. why loop items element, then set image from results elements?
    – caoglish
    Jul 26, 2013 at 0:01
  • I, all the time, try to get new image by looping , the first line is working out (no problem with the API ! )
    – Epsilon_G
    Jul 26, 2013 at 0:04
  • what i mean if 'items' only has one element. this loop only runs once. no matter how many 'results' in 'data'
    – caoglish
    Jul 26, 2013 at 0:08

1 Answer 1

0

you need to loop data.results, not data.items

see:jsfiddle

    success: function (data) {

           var $ul=$('<ul/>');

     $.each(data.results, function(i,item){ // on this line
        var img = item.value;  
         $ul.append($('<li/>').append($('<img/>').attr('src',img)   ));
      });

       $('#result').html($ul);

    }
3
  • What if I wanna add a title under every image . How can I do that !
    – Epsilon_G
    Jul 26, 2013 at 1:42
  • that's ohter jquery thing. title tag could be .append() in $('<li/>') or $('<img/>').after() in your loop, it's up to you. if you want beautiful title, check third party library.
    – caoglish
    Jul 26, 2013 at 4:23
  • caoglish : Can you please check this post : stackoverflow.com/questions/17922437/parsing-in-jquery
    – Epsilon_G
    Jul 29, 2013 at 11:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.