开发者

Adding 1 to an instance variable, thats in a partial, rendered through JQuery. Rails3

Hey guys, so I realize this might be a little convoluted, but here is what my code looks like, and what I'm trying to do:

#new.html.erb

<% @tag_counter = 0 %>

Javascript code here, that says, wh开发者_Python百科en a specific button is clicked, append the partial _tag.html.erb to a div below

#_tag.html.erb

<div id="tag-id-<%= @tag_counter %>">Div here</div>
<% @tag_counter = @tag_counter+1 %>

So the problem I'm having is that the @tag_counter value isn't changing. Its remaining at 0 and each div that is appended has the same ID. Any idea how I can make this work?


Each _tag.html.erb is rendered by a new HTTP request and will have all variables independent from all the other calls. Also note that your Ruby code does not have access to the page other than what the callback explicitly provides, so you cannot check what is already on the page.

Either include a counter in the request (from JavaScript), set it after the fact (also from JavaScript), or create random IDs.


Have a look here: http://guides.rubyonrails.org/layouts_and_rendering.html#using-partials

In 3.4.7, you'll see that counter do exist for partials, just use it the Rails way.


I do something similar, though this may not be the answer you're looking for.

When someone votes in my application, I have the signal fired via AJAX.

$(".vote_link").live("click", function (){
    $.ajax({type: "GET", url: $(this).attr("href"), dataType: "script"});
    return false;
});

This loads an href that targets a js file that says this :

== $(".event_#{@event.id}_score").html("#{ escape_javascript(@event.score.to_s)}");

The event is targeted by its unique id with its class, and Jquery handles swapping out just the number, rather than loading an entire partial like what I believe you're trying to do.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜