Access DOM element inside $.getJSON

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?

Answers


You 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;
    });
});

Need Your Help

how to send rich text message in system.net.mail

.net

how to send rich text message in system.net.mail need code for send a mail as html

Difference between a static and a final static variable in Java

java

Generally, final static members especially, variables (or static final of course, they can be used in either order without overlapping the meaning) are extensively used with interfaces in Java to d...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.