Can I pass $(this) to the .getJSON callback function? any workaround?

javascript, jquery

Solution

Just assign it outside of the callback (like I am setting `self`) and then use inside callback (by referring to the variable you have set):

$('ul.sample li').each(function () {

    var self = $(this); // using self to store $(this)
    var url = 'http://sampleurl/api/url?' + self.attr('rel');

    $.getJSON(url, function (data) {
        // now retrieving self - it is accessible from the callback
        self.find('img').attr('src') = data.thumbnail_url;
    });

});

The reason for that is because `this` is different in callback for `.each()` than in callback for `$.getJSON()`.

Problem

I tried to get the value of rel on each li and pass it to the .getJSON function. I then want to add the thumbnail_url value from the callback to the image tag of the li descendants . My question is how could I pass the $(this) object to the callback function. It seems the $(this) is null. ``` $('ul.sample li').each(function () { var url = 'http://sampleurl/api/url?' + $(this).attr('rel'); $.getJSON(url, function (data){ $(this).find('img').attr('src') = data.thumbnail_url; }) }); ``` HTML: ``` <ul class="sample"> <li rel="value1"> <img src=""> </li> <li rel="value2"> <img src=""> </li> </ul> ```

Original source