Ruby on Rails:在<%=%>中使用javascript变量Html.erb中的标签 [英] Ruby on rails: using javascript variable in <%= %> tags in Html.erb
问题描述
我试图在<%=%>标记中使用插入Javascript变量,但是它会打印出冗长的变量名称。这是我的代码
I am trying to use insert an Javascript variable in the <%= %> tags but it prints the variable name verbose. Here is my code
<script>
function getGraph(agency,device_id)
{
var i = document.createElement('img');
i.src = '<%= show_graph_hcfcd_url('device_id') %>';
$(graphDiv).appendChild(i);
}
</script>
现在问题是生成的URL很好,除了device_id的值而不是value, device_id出现在其余网址。
Now the Problem is URL gets generated just fine except instead of value of device_id, 'device_id' appears in the rest url.
任何线索如何克服这个问题?
Any clues how to get over this?
推荐答案
<%=%>
将解释代码服务器
,并且可以在客户端上更改javascript变量。
and javascript variable is available to change on the client. So doing
<%= show_graph_hcfcd_url('device_id') %>
可能不是这样做的正确方法。
is probably not be the correct way of doing this.
您可能希望尝试将url放入元素的数据属性中:
You might want to try to put the url(s) in the data attibute of the element:
<div id="device_id" data-url="<%= show_graph_hcfcd_url(@device.id) %>">...</div>
<script>
function getGraph(agency,device_id)
{
var i = document.createElement('img');
i.src = $(device_id).data("url");
$(graphDiv).appendChild(i);
}
</script>
另请参见
http://railscasts.com/episodes/324-passing-data-to-javascript
有一个很好的宝石可以做到这一点,称为 gon
There's a good gem to do this called "gon"
这篇关于Ruby on Rails:在<%=%>中使用javascript变量Html.erb中的标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!