2011-04-14 42 views
0

我有一個Rails應用程序,它具有一些簡單的功能,允許用戶保存/取消保存帖子。Rails 3使用Ajax更新頁面上的多個相同元素

它這樣做是好的,ajaxy,像這樣:

觀點:

<p id="save_<%= frugle.id %>"> 
    <%= link_to "Save", new_saveds_path(current_user.id, :post_id => post.id), :remote => true %> 
</p> 

控制器:

class SavedsController < ApplicationController 
    def new 
    @follow = Saved.create(:user_id => current_user.id, :post_id => params[:post_id]) 
    @post = Post.find params[:post_id] 
    render :update do |page| 
     page.replace_html "save_#{@post.id}", "#{link_to "Unsave", saveds_path(current_user.id, :post_id => @post.id), :method => :delete, :remote => true }" 
    end 
    end 

這工作得很好,很正常。我的問題有時會出現在主頁上,用戶有很多正在查看的帖子,偶爾同一帖子會出現兩次。如果用戶去保存這篇文章,那麼上面的RJS將會改變第一個p,然後停止。有沒有辦法在單個頁面上用該ID更新所有的p?

這樣做合適嗎?

謝謝!

回答

0

您不能「用該ID更新所有'p',因爲根據定義,頁面上只有一個元素具有給定的id。

但是,如果你給你所有的<p>根據自己軌道ID,你可以做你想做的。

例子:

<p class="object-1234">test</p> 
<p class="object-5678">another test</p> 
<p class="object-1234">test</p> 

現在你可以這樣做:

$('.object-1234').hide() 

,並得到預期的效果。

編輯
此外,這假設你在你的AJAX的看法使用jQuery。我強烈建議你這樣做 - 它比內置的rjs更有用。
這裏是關於它的截屏:http://railscasts.com/episodes/136-jquery

+0

我同意,我想去jquery,但該網站大多是使用默認的rjs構建的。是否可以使用RJS通過類而不是id更新元素? – goddamnyouryan 2011-04-14 09:35:17

+1

page.select('。someclass')。each do | element | page.replace_html元素,「

OHAI

」 end – x10 2011-04-14 09:40:00

相關問題