问题是页面上的所有“进入”按钮都具有相同的ID,并且所有“撤消”具有相同的ID,因此单击一个可以抵消其他ID。按钮也只切换一次。我对rails,CSS,ajax很新,我很感激帮助,谢谢。
Micropost_Helper.rb
def toggle_like_button(micropost, user)
if user.voted_for?(micropost)
link_to "undo", like_micropost_path(micropost), :class => "btn btn-mini btn-primary", :id =>"unvote_form", :remote => true
else
link_to "Into it!", like_micropost_path(micropost), :class => "btn btn-mini btn-primary", :id =>"vote_form", :remote => true
end
end
Micropost Controller
def like
@micropost = Micropost.find(params[:id])
if @micropost.user_id != @current_user
if @current_user.voted_for?(@micropost)
@current_user.unvote_for(@micropost)
respond_to do |format|
format.html { redirect_to :back }
format.js
end
else
@current_user.vote_for(@micropost)
respond_to do |format|
format.html { redirect_to :back }
format.js
end
end
end
end
VIEW / microposts / like.js.erb< - 用这个我只能点击按钮一次,在这里也需要帮助
$("#vote_form").html("undo")
$("#unvote_form").html("Into it!")
答案 0 :(得分:3)
您应该将uniq id附加到每个按钮,如下所示:
def toggle_like_button(micropost, user)
if user.voted_for?(micropost)
link_to "undo", like_micropost_path(micropost), :class => "btn btn-mini btn-primary", :id =>"unvote_form_#{micropost.id}", :remote => true
else
link_to "Into it!", like_micropost_path(micropost), :class => "btn btn-mini btn-primary", :id =>"vote_form_#{micropost.id}", :remote => true
end
end
然后你可以在你的like.js.erb中引用一个按钮:
$("#vote_form_<%=@micropost.id%>").html("undo")
$("#unvote_form_<%= @micropost.id%>").html("Into it!")
这样你就会拥有有效的HTML,你的问题就应该解决了。