开发者

Evaluation of a Ruby variable in a jQuery statement passed to :onclick in Rails

I'm iterating over records and want to create the toggle-options for records but I can't replace the div-id with the records:

<% for bill in @bills %>
<% tmp = "test"%>
<%= link_to '&raquo now','#', :onclick => '$("#{tmp}").toggle();' %>

Instead of getting:

<a href="#" onclick="$(&quot;#test&quot;);">&raquo now</a>

I'm getting:

<a href="#" onclick="$(&quot;#{tmp}&开发者_StackOverflow中文版amp;quot;).toggle();">&raquo now</a>

So there isn't evaluation of the ruby variable in the string. How can I do this?

Thanks for your help and I'm new in jQuery.


In order for string interpolation to work in Ruby the string needs to be enclosed in double quotes i.e. rather than:

:onclick => '$("#{tmp}").toggle();'

use one of the following alternatives:

  • surround the string in double quotes and escape the literal double quotes that occur in the string:

    onclick => "$(\"#{tmp}\").toggle();

  • use the %Q notation then you won't need to escape the double quotes:

    :onclick => %Q{$("#{tmp}").toggle();}

  • use double quotes in the Ruby code and single quotes in the JavaScript that will be generated:

    :onclick => "$('#{tmp}'.toggle();"

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜