I'm developing an application that iterates over some DOM
elements, and performs an Ajax
request for each one of those elements. The problem is that I cannot access each DOM
element inside the callback function.
$('.class').each(function() {
$.getJSON(url, function(data) {
$(this).attr('id', data.id); // $(this) is not accessible
});
});
Is there a way to solve this?
I'm developing an application that iterates over some DOM
elements, and performs an Ajax
request for each one of those elements. The problem is that I cannot access each DOM
element inside the callback function.
$('.class').each(function() {
$.getJSON(url, function(data) {
$(this).attr('id', data.id); // $(this) is not accessible
});
});
Is there a way to solve this?
Share Improve this question asked Jun 9, 2014 at 8:07 jeojavijeojavi 8861 gold badge7 silver badges15 bronze badges4 Answers
Reset to default 6You should use a variable, as the value of this
changes for each function call, and inside the callback for $.getJSON this
is no longer the element.
$('.class').each(function() {
var self = this;
$.getJSON(url, function(data) {
self.id = data.id;
});
});
Another option would be the built in arguments in each()
$('.class').each(function(index, element) {
$.getJSON(url, function(data) {
element.id = data.id;
});
});
You could do this to not have to execute an assignment.
$.getJSON(url, function(data) {
$(this).attr('id', data.id); // $(this) is accessible
}.call(this));
DEMO: http://jsfiddle/8EWvC/4/
One way to do it would be to use Function#bind
, like this:
$('.class').each(function() {
$.getJSON(url, function(data) {
$(this).attr('id', data.id);
}.bind(this)); // Pass `this` into the getJSON and now `this` should be the DOM element
});
What this does is that whatever you pass into bind
will be set to this
inside the function. You can find out more by reading the MDN here
Either you can cache your selector in a variable like it:
$('.class').each(function() {
var $this = $(this); // cache it here
$.getJSON(url, function(data) {
$this.attr('id', data.id); // $(this) is not accessible
});
});
or if you are able to change your $.getJson()
to traditional $.ajax()
then you can use context:this,
param:
$('.class').each(function() {
$.ajax({
url : url,
dataType: 'json',
context: this,
success: function(data) {
this.id = data.id; // $(this) is not accessible
}
});
});