javascript - passing a rails variable into a js function - Stack Overflow

admin2025-04-18  0

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

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

#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.

the corresponding js function is:

: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?

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

Any help would be really appreciated.

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

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

#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.

the corresponding js function is:

: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?

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

Any help would be really appreciated.

Share asked Nov 27, 2010 at 9:55 mtaymtay 1,3164 gold badges20 silver badges36 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 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.

Using

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

can be a solution, or check the generated sourc code

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1744949945a276271.html

最新回复(0)