从Rails link_to调用jQuery函数

时间:2012-04-13 02:50:00

标签: javascript jquery ruby-on-rails link-to

我有一个ruby循环,可以创建一个评论列表..

我想知道在这种情况下我是否可以将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 %>

我希望像

这样的东西
    <% @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 %>

我知道它不起作用,但我想知道有一种简单的方法可以实现这种功能吗?

谢谢!

3 个答案:

答案 0 :(得分:6)

你可以这两种方式。

第一个是在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 %>

第二个是将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>

如果您想要链接标记的内容,请将'CONTENTS OF HTML'替换为$(this).html()

答案 1 :(得分:3)

此外,我实际上发现了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>

答案 2 :(得分:2)

您可能希望使用事件委派,因为您似乎会创建大量注释。

所以,从赠款中借用类似的东西:

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