我有一个用户列表,每个用户的名字旁边都有一个关注按钮。 'follow'请求通过ajax完成,然后按下按钮变为'unfollow'按钮。
I have a list of users who each have a 'follow' button next to their name. The 'follow' request is complete via ajax and the follow button then changes to a 'unfollow' button.
我的代码在列出一个用户的情况下工作正常(并且还有后端工作,列出了多个用户)但我想要的是列出多个用户,然后以某种方式绑定按照每个按钮所包含的特定元素'.follow_form'的请求,以便只有一个孩子'关注'按钮被点击更改为'取消关注'。
My code works fine with one user listed (and also works back-end with multiple users listed) but what I would like is to list multiple users and then somehow bind the follow request to the specific element, '.follow_form' which each button is contained in, so that only the one child 'follow' button which is clicked changes to the 'unfollow'.
我遇到绑定问题的jquery代码如下:
The jquery code which I'm having trouble binding is as follows:
/create.js.erb $(".follow_form").html("<%= escape_javascript(render('users/unfollow')) %>")和
/destroy.js.erb $(".follow_form").html("<%= escape_javascript(render('users/follow')) %>")提交表单时,显然所有.follow_form元素都已更改,但我无法弄清楚如何绑定正确的元素?
When the form is submitted obviously all the .follow_form element are changed but I can't work out how to bind the correct element?
其中一件我试过的代码(对于create.js.erb)是:
One of a few pieces of code I tried (for create.js.erb) was:
$("input.follow").bind( function() { $(this).closest(".follow_form").html("<%= escape_javascript(render('users/unfollow')) %>") });但没有回复???
推荐答案您可能应该在 ajax:success 回调中执行此操作,因为它会自动绑定到对象。
You should probably be doing this in an ajax:success callback instead since it is automatically bound to the object.
你可以删除那些 .js.erb 文件,只需在控制器中渲染它们:
You can delete those .js.erb files and just render them in the controller:
def create # creation code here # now render the response render :json => { :new_button => render_to_string( :partial => 'users/unfollow' ) }, :status => :created end def destroy # deletion code here # now render the response render :json => { :new_button => render_to_string( :partial => 'users/follow' ) }, :status => :no_content end然后在你的javascript文件中:
Then in your javascript file:
$('input.follow, input.unfollow').live('ajax:success', function(data, json, response) { $(this).closest(".follow_form").html(json.new_button); }); $('input.follow, input.unfollow').live('ajax:error', function(data, xhr, response) { // handle the ajax error here });更多推荐
将ajax请求绑定到特定元素Rails 3.1
发布评论