Evan
Evan

Reputation: 1737

Appending HTML via jQuery .each()

I have what seems like a simple problem in my Rails 3.1 app:

I have a series of divs with a class name of 'feed-row':

<% @feeds.each do |feed| %>
   <div class="feed-row" data-feedid="<%= feed.id %>">  
   </div>
   <div class="clear">
   </div>
<% end %>

The idea is this:

I will gather all of the divs into a collection, loop over each item, pass its data tag to a page that returns an html fragment, then append that fragment into the appropriate div.

The javascript I have to pull the data looks like this:

<script type="text/javascript" charset="utf-8">
    $(".feed-row").each(function(){     
        $.get("/retrieve/" + $(this).attr("data-feedid"), function(d) {         
            $(this).append(d);
        }); 
    }); 
</script>

Looking at the requests in Chrome's inspector, I can see that the call out going out fine and returning the HTML fragment I intend:

enter image description here

So, with this HTML fragment, I want to inject it into the current row in my loop.

The Problem Is This

None of my HTML fragments appear on my page - it is simply missing the data pulled via the jQuery .get() method.

When I inspect the DOM elements, it appears that nothing has been injected inside the elements at all:

<div class="feed-row" data-feedid="5"></div>

I am sure I am missing something simple here - why is the data I pull down via jQuery never getting to my DOM elements?

Thanks for any assistance!

Upvotes: 0

Views: 100

Answers (1)

RightSaidFred
RightSaidFred

Reputation: 11327

Because this in the $.get callback is not the same as it is in the .each() callback.

$(".feed-row").each(function(){    
    var self = this; 
    $.get("/retrieve/" + $(this).attr("data-feedid"), function(d) {         
        $(self).append(d);
    }); 
}); 

What I did was I referenced the element using the self variable, then used that variable in the $.get callback to reference the element.

So every iteration of .each() will have a unique self variable, as well as a unique $.get callback that references that the unique self variable in its scope.

Upvotes: 3

Related Questions