Using $(this) in .js.erb file - Ruby on Rails AJAX

2020-07-23 06:15发布

I am using Rails3 with jQuery and attempting to do simple ajax calls. I have a link that displays the current status (online/offline) of an application. When clicked it will update the status.

link_to app.status, { :controller => :apps, :action => :live_status, :id => app }, {:remote => true, :class => "#{app.status} status"}

live_status.js.erb:

$(this).fadeOut();
$(this).parent().html("<%= escape_javascript(status_link(@wowza_app)) %>");
$(this).fadeIn();

status_link will return the updated link_to

However $(this) isn't working how I envision. How can I update the clicked status with the new status?

2条回答
太酷不给撩
2楼-- · 2020-07-23 06:34

You should give the element you want to update an ID (I added an element to the hash at the very end):

link_to app.status, { :controller => :apps, :action => :live_status, :id => app }, {:remote => true, :class => "#{app.status} status", :id => app.id}

Now, you can use that same identifier to select the right element with jQuery:

$("#<%= @wowza_app.id %>").fadeOut();
$("#<%= @wowza_app.id %>").parent().html("<%= escape_javascript(status_link(@wowza_app)) %>");
$("#<%= @wowza_app.id %>").fadeIn();

Of course, this assumes that @wowza_app has a method called id that returns the same ID of the link, but you can modify the variables as necessary to select the element with the right ID.

查看更多
神经病院院长
3楼-- · 2020-07-23 06:36

you should use a selector. When you have that code interpreted in the ajax response, jQuery doesn't know what "this" are you referring. Better use something like:

$('#my-special-div').fadeOut();
$('#my-special-div').parent().html("<%= escape_javascript(status_link(@wowza_app)) %>");
$('#my-special-div').fadeIn();
$('#my-special-div').hide(2000, function () {
    $(this).remove();  // here jQuery knows you are talking about 'my-special-div'
});
查看更多
登录 后发表回答