Call jQuery function from Rails link_to

I have a ruby ​​loop that creates a list of comments.

I wonder if I can attach the jQuery function to the Rails link_ to the helper in this case?

<% @video.phrases.each do |phrase| %> <div class = "span4" id ="comment" ><%= phrase.content %></div><a id ="ff" ><%= image_tag("ff.png", :size=> "32x32" )%></a> <% end %> 

I hope for something like

  <% @video.phrases.each do |phrase| %> <div class = "span4" id ="comment" ><%= phrase.content %></div><%= link_to (image_tag("ff.png", :size=> "32x32" ), html => {<script>$("#video_div").html('CONTENTS OF HTML');</script>} :remote => true %> <% end %> 

I know this won't work, but I wonder if there is an easy way to achieve this functionality?

Thanks!

+6
source share
3 answers

You can do this in two ways.

The first is to add the html attribute to link_to:

 <% @video.phrases.each do |phrase| %> <div class = "span4" id ="comment" > <%= phrase.content %> </div> <%= link_to (image_tag("ff.png", :size=> "32x32" ), html => {:onclick => "$('#video_div').html('CONTENTS OF HTML');"} :remote => true %> <% end %> 

Second, separate Javascript from Ruby:

 <% @video.phrases.each do |phrase| %> <div class = "span4" id ="comment" > <%= phrase.content %> </div> <%= link_to (image_tag("ff.png", :size=> "32x32" ) :remote => true %> <% end %> <script type="text/javascript"> $('a').click(function(){ $("#video_div").html('CONTENTS OF HTML'); ); </script> 

If you want the contents of the link tag, replace 'CONTENTS OF HTML' with $(this).html()

+6
source

In addition, I really learned about the Rails helper agent link_to_function and was able to achieve the desired behavior with:

 <% @video.phrases.each do |phrase| %> <div class = "span4" id ="comment" ><%= phrase.content %></div><a id ="ff"> <%= link_to_function image_tag("ff.png", :size=> "32x32" ), "use_comment('#{phrase.comment}')"%> </a> 
+3
source

You might want to use event delegation, as it seems that you will create a large number of comments.

So, borrowing from the grant something like:

 <% @video.phrases.each do |phrase| %> <div class = "span4" id ="comment" > <%= phrase.content %> </div> <%= link_to (image_tag("ff.png", :size=> "32x32" ) :remote => true %> <% end %> 
 <script type="text/javascript"> $("#comment-wrapper-name-here").on("click", "a", function() { $("#video_div").html('CONTENTS OF HTML'); ); </script> 
+2
source

Source: https://habr.com/ru/post/913101/


All Articles