0

我想要在单击时更改为取消关注的关注按钮。但是当它提交表单时,它根本不做任何事情。为什么?

我的代码是这样的

-----动作(users_controller.rb)-----

 def set_follow
   friend = User.find_by_username(params[:username])
   if f = Friendship.find(:first, :conditions => { :user_id => current_user.id, :friend_id => friend.id})

     f.destroy
     flash[:notice] = "Now added to follow list"
     respond_to do |format|
       format.html { redirect_to set_follow }
       format.js
     end
     #redirect_to :back
   else
     Friendship.create(:user_id => current_user.id, :friend_id => friend.id)
     flash[:error] = "Now deleted from follow list"
     respond_to do |format|
       format.html { redirect_to set_follow }
       format.js
     end
     #redirect_to :back
   end
end

-----表单(用户/index.html.erb)-----

<div id="follow_status">
   <% if user_signed_in? && current_user.friends.find_by_id(user.id) %>
     <%= link_to sanitize('<i class="icon-remove icon-white"></i> ') + 'Un-Follow', follow_user_path(user.username), :class => 'btn', remote: true %>
   <% elsif current_user != user %>
     <%= link_to sanitize('<i class="icon-ok icon-white"></i> ') + 'Follow', follow_user_path(user.username), :class => 'btn btn-primary', remote: true %>
   <% end %>
 </div>

-----JS 视图(set_follow.js.erb)--

$("#follow_status").html("<%= escape_javascript(render f) %>");
4

1 回答 1

1

有点不同的方法,但我会用 JQuery 做到这一点

$('.btn').click( function() {
    if( $('.btn').html() == 'Follow') {
        $('.btn').html('Unfollow');
    }
    else if( $('.btn').html() == 'Unfollow') {
        $('.btn').html('Follow');
    }

});

​这只是你如何做到这一点的一个例子。您可能希望在 jquery 中使用更具体的类链

于 2012-12-05T18:01:10.350 回答