开发者

image_to_function in Rails

I have this method on rails so that I have an image calling a javascript function

def image_to_function(name, function, html_options = {})
  html_options.symbolize_keys!
  tag(:input, html_options.merge({ 
      :type => "image", :src => image_path(name),
      :onclick => (html_options[:onclick] ? "#{html_options[:onclick]}; " : "") + "#{function};" 
      }))
end

I grabbed this 开发者_如何学Ccode from the application helper of the redmine source code, the problem I'm having is that when I click on the image it's sending a POST, does some one know how can I stop that?

This is how I'm using it

<%= image_to_function "eliminar-icon.png", "mark_for_destroy(this, '.task')" %>

Thanks alot!


If your onclick event returns true, your browser follows the href, if it returns false, your browser won't follow. So here's the trick:

def image_to_function(name, function, html_options = {})
  html_options.symbolize_keys!
  tag(:input, html_options.merge({ 
      :type => "image", :src => image_path(name),
      :onclick => (html_options[:onclick] ? "#{html_options[:onclick]}; " : "") + "#{function}; return false;" 
      }))
end

Alternatively let #{function} return true or false and insert the return statement in front of the interpolation. This way the called function could control if the browser should follow the href.

PS: You probably want to replace tag(:input... with a link_to_function(image_path(name), ... construct so you can use it outside of forms, too.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜