Rails - Access AJAX Triggering Element in Callback

别等时光非礼了梦想. 提交于 2019-12-11 23:58:16

问题


I have a view, say show.js.erb. And I have a link in another view such that

link_to "MyLink", my_object_path, :remote => true

successfully returns the show.js.erb view. My question is, from within that view, is there any way to access the element that triggered the AJAX call without having to resort to generating an id specific to individual elements a la ...

I want to be able to use this view callback to open a small dialog next to whatever element was clicked on, but I can't seem to find a way to access the triggering element.

I tried using $(this) but that doesn't work.

I'd like to do something along the lines of

$(this).after("some new html here");

回答1:


My solution was to bind a pre-submit class to the element, in my case a popup modal window. It's a similar solution to the post linked to above in that it uses the pre-submit bindings, but tailored to use classes instead.

In public/javascripts/application.rb:

jQuery(function($) { 
  $(".poppable").bind("ajax:loading", function() { $(this).addClass("popped"); });
});

Then in my view for the popup content (e.g. app/views/mymodel/popup.js.erb):

var p = $(".poppable.popped");
p.removeClass("popped");
/* Do what I need to with p ... */

If this doesn't look kosher, I'm all ears but it works for now.



来源:https://stackoverflow.com/questions/4781824/rails-access-ajax-triggering-element-in-callback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!