简体   繁体   English

从Rails link_to调用jQuery函数

[英]Call jQuery function from Rails link_to

I have a ruby loop that creates a list of comments.. 我有一个ruby循环,创建一个注释列表..

I wonder if I can attach jQuery function to Rails link_to helper in this case? 我想知道在这种情况下我是否可以将jQuery函数附加到Rails link_to helper?

    <% @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: 第一个是在link_to上添加一个html属性:

<% @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: 第二个是将Javascript与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() 如果你想要链接标签'CONTENTS OF HTML'$(this).html()替换'CONTENTS OF HTML'

Also I actually found out about Rails link_to_function helper and was able to achieve the desired behavior with: 此外,我实际上发现了Rails link_to_function助手,并且能够通过以下方式实现所需的行为:

<% @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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM