Ruby on rails:在 Html.erb 的 <%= %> 标签中使用 javascript 变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5940871/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ruby on rails: using javascript variable in <%= %> tags in Html.erb
提问by Shaunak
I am trying to use insert an Javascript variable in the <%= %> tags but it prints the variable name verbose. Here is my code
我正在尝试在 <%= %> 标签中插入一个 Javascript 变量,但它会详细打印变量名称。这是我的代码
<script>
function getGraph(agency,device_id)
{
var i = document.createElement('img');
i.src = '<%= show_graph_hcfcd_url('device_id') %>';
$(graphDiv).appendChild(i);
}
</script>
Now the Problem is URL gets generated just fine except instead of value of device_id, 'device_id' appears in the rest url.
现在的问题是 URL 生成得很好,除了 device_id 的值之外,'device_id' 出现在其余 url 中。
Any clues how to get over this?
任何线索如何克服这个?
回答by montrealmike
<%= %>
will interpret the code on the server
<%= %>
将解释服务器上的代码
and javascript variable is available to change on the client. So doing
并且 javascript 变量可以在客户端上更改。这样做
<%= show_graph_hcfcd_url('device_id') %>
is probably not be the correct way of doing this.
可能不是这样做的正确方法。
You might want to try to put the url(s) in the data attibute of the element:
您可能想尝试将 url(s) 放在元素的数据属性中:
<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>
also see
另见
http://railscasts.com/episodes/324-passing-data-to-javascript
http://railscasts.com/episodes/324-passing-data-to-javascript
There's a good gem to do this called "gon"
有一个很好的宝石可以做到这一点,叫做“gon”
回答by Shaunak
Here is how i have solved this for now:
这是我现在解决这个问题的方法:
<script>
function getGraph(agency,device_id)
{
var i = document.createElement('img');
var url = '<%= show_graph_hcfcd_url('device_id') %>'; //new change
url = url.replace('device_id',""+(device_id*1000)); //new change
i.src = url;
$(graphDiv).innerHTML = "";
$(graphDiv).appendChild(i);
}
</script>
The lines in the bold show what i did. Basically replaced the "device_id" in the url with its value.
粗体中的线条显示了我所做的。基本上用它的值替换了 url 中的“device_id”。
But I am still hoping for a more elegant solution.
但我仍然希望有一个更优雅的解决方案。