将rails变量传递给js函数

时间:2021-09-22 21:32:25

Apologies -- I'm a newbie using Ruby on Rails. Still a little confused about how it works.

道歉 - 我是使用Ruby on Rails的新手。关于它是如何工作仍然有点困惑。

Right now, in my view, under my scroller div, I have this code:

现在,在我看来,在我的滚动条div下,我有这个代码:

#scroller
 -@other_images.each do |img|
  .thumbnail_wrapper
    .thumbnail_image
      =image_tag img.image.url(:thumbnail), :class => 'button' , :onClick => "replaceImg(img.id);"

@other_images is a variable that holds all the thumbnail images I want to display on the page. Clicking on one will refresh a div elsewhere with its own big image.

@other_images是一个变量,它包含我想在页面上显示的所有缩略图图像。单击其中一个将使用自己的大图像刷新其他地方的div。

the corresponding js function is:

相应的js函数是:

:javascript
 function replaceImg(id){
  var url = '/images/refresh/' + id;
  new Ajax.Updater('content_image', url);
 }

This works if I just write in a valid url. But passing the param "id" into the js function does not work. I'm at a loss... what am I missing?

如果我只是写一个有效的网址,这是有效的。但是将参数“id”传递给js函数是行不通的。我很茫然......我错过了什么?

How do I pass this rails variable -- img --- into my js? It's just stuck in that loop.

如何将这个rails变量 - img ---传递给我的js?它只是停留在那个循环中。

Any help would be really appreciated.

任何帮助将非常感激。

2 个解决方案

#1


6  

Try this:

尝试这个:

img.image.url(:thumbnail), :class => 'button' , :onClick => "replaceImg(#{img.id});"

The #{...} construct executes the ruby code within the curly brackets and replaces the entire construct with the result. Can be used anywhere you want to replace part of a string with some content from a ruby variable or method.

#{...}构造在大括号内执行ruby代码,并用结果替换整个构造。可以在任何想要使用ruby变量或方法中的某些内容替换字符串的一部分的地方使用。

#2


0  

Using

运用

=image_tag img.image.url(:thumbnail), :class => 'button' , :onClick => "replaceImg('#{img.id}');"

= image_tag img.image.url(:thumbnail),:class =>'button',:onClick =>“replaceImg('#{img.id}');”

can be a solution, or check the generated sourc code

可以是一个解决方案,或检查生成的源代码

#1


6  

Try this:

尝试这个:

img.image.url(:thumbnail), :class => 'button' , :onClick => "replaceImg(#{img.id});"

The #{...} construct executes the ruby code within the curly brackets and replaces the entire construct with the result. Can be used anywhere you want to replace part of a string with some content from a ruby variable or method.

#{...}构造在大括号内执行ruby代码,并用结果替换整个构造。可以在任何想要使用ruby变量或方法中的某些内容替换字符串的一部分的地方使用。

#2


0  

Using

运用

=image_tag img.image.url(:thumbnail), :class => 'button' , :onClick => "replaceImg('#{img.id}');"

= image_tag img.image.url(:thumbnail),:class =>'button',:onClick =>“replaceImg('#{img.id}');”

can be a solution, or check the generated sourc code

可以是一个解决方案,或检查生成的源代码