Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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>
like image 457
seanbun Avatar asked May 22 '12 01:05

seanbun


Video Answer


2 Answers

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().

like image 61
Tadeck Avatar answered Sep 23 '22 00:09

Tadeck


If you use $.ajax instead of $.getJSON, you could use the context option:

$('ul.sample li').each(function () {
    var url = 'http://sampleurl/api/url?' + $(this).attr('rel');
    $.ajax({
        url : url,
        dataType : 'json',
        context : this,
        complete : function (data) {
            // 'this' will be what you passed as context 
            $(this).find('img').attr('src') = data.thumbnail_url;
        }
    });
});
like image 30
bfavaretto Avatar answered Sep 27 '22 00:09

bfavaretto