I have a ruby loop that creates a list of comments..
I wonder if I can attach jQuery function to Rails link_to 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 am hoping 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 it won't work, but I wonder is there an easy way to achieve this kind of functionality?
Thanks!
You can do this two ways.
The first is the add an html attribute on the 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 %>
The second is to separate the 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, substitute 'CONTENTS OF HTML'
for $(this).html()
Also I actually found out about Rails link_to_function helper 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>
You might want to use event delegation, since it seems like you'll be creating a large number of comments.
So, borrowing from 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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.