2011-11-04 167 views
0

我有这样的代码:是否有可能将Rails变量传递给JavaScript函数?

<% @hello = "hello world" %> 
<td class="text"><%= link_to project.name, project, 
        :onmouseout=>"hidetooltip()", 
        :onmouseover=>"showDescription()"%> 
</td> 

showDescription JavaScript函数需要一个字符串参数。我想通过@hello作为参数到showDescription。我尝试了一切,似乎无法让它工作。

回答

2

在这里你去:

<% @hello = "hello world" %> 
<%= link_to project.name, project, :onmouseout=>"hidetooltip()", 
            :onmouseover=>"showDescription(#{ @hello.to_json })"%> 
+0

哇...谢谢! – Minh

+0

这有用吗?逗号或to_json似乎缺少。 (顺便说一句,为什么{}中的非惯用空格?) – tokland

+0

@tokland:它只是文本,所以不需要使用'to_json' – apneadiving

0

另一种方式来做到这一点是使用宝石client variable。它可以帮助你轻松地做到这一点