1

I am using lis to obtain a list of <li> from my DOM, and in each LI and update the projectPhoto after the ajax call. But my "li" in the callback function always referring to the last item in lis, is there any way to overcome this, or such as pass as value ?

p/s: I am pretty sure this has been discussed before just that I can't reach it with the right terminology. Apology in advance.

var lis = $('.porject_list li');
   for (var i = 0; i < lis.length; i++) {

        var li = lis.eq(i);
var projectId = li.attr('data-project-id');


            $.get("/webapi/projects/projectphoto/" + projectId, function (res) {
                $("img", li).attr('src', res);
            });
    }
drhanlau
  • 2,517
  • 2
  • 24
  • 42

3 Answers3

2

You may try this (Just wrap the ajax call in a function)

(function(current){
    $.get("/webapi/projects/projectphoto/" + projectId, function (res) {
        $("img", current).attr('src', res);
    });
})(li);

Update :

I didn't notice var li = lis.eq(pos);, what is this, anyways, you can use

var li = lis[i];

to get the current li in the loop.

The Alpha
  • 143,660
  • 29
  • 287
  • 307
2

you used jquery so you can used $.each of jquery. try this code if it can help

$(".porject_list li").each(function(i, elem) {
    var projectId = $(this).attr('data-project-id');
    var $li = $(this);
    $.get("/webapi/projects/projectphoto/" + projectId, function (res) {
         $li.find("img").attr('src', res);
    }); 
}); 
kashimu
  • 174
  • 2
  • 9
0

I think this is a good reference for you.

http://api.jquery.com/each/

delroekid
  • 88
  • 7