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>
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()
.
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;
}
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With