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>
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>
Share
Improve this question
edited May 22, 2012 at 23:35
seanbun
asked May 22, 2012 at 1:57
seanbunseanbun
9423 gold badges15 silver badges32 bronze badges
3
- SyntaxError: Unexpected identifier(unexpected_token_identifier) – Musa Commented May 22, 2012 at 2:00
- 1 Javascript closures strike again! – Spencer Ruport Commented May 22, 2012 at 2:02
-
Besides the original issue, you also have another problem: It should be
var url = 'http://sampleurl/api/url?'+$(this).attr('rel');
– Steve Commented May 22, 2012 at 2:04
2 Answers
Reset to default 8Just 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,
plete : function (data) {
// 'this' will be what you passed as context
$(this).find('img').attr('src') = data.thumbnail_url;
}
});
});