[英]How to access the current rails object id in javascript
If I am on a view, how can I access the ID of the ruby object that is currently represented by that view? 如果我在视图上,如何访问该视图当前表示的ruby对象的ID?
Eg If I am on blah.com/jobs/1
how do I get 1? 例如,如果我在
blah.com/jobs/1
,我怎么得到1?
I thought about trimming the current URL but that seems way too brittle, especially given I have nested resources. 我考虑过修剪当前的URL,但这似乎太脆弱了,特别是考虑到我有嵌套资源。 The only other easy way I can think of is to have a hidden field but it seems silly to have a hidden input on a show page where there aren't any forms.
我能想到的另一个简单的方法就是拥有一个隐藏的字段,但在没有任何表格的节目页面上隐藏输入似乎很愚蠢。
You're right that parsing the URL is a bad idea, you're better off explicitly supplying it somewhere. 你解析URL是个坏主意,你最好明确地在某处提供它。
You could attach a data-job-id
attribute to a standard element in the HTML, perhaps even <body>
. 您可以将
data-job-id
属性附加到HTML中的标准元素,甚至可能是<body>
。 Then your JavaScript could do things like this: 然后你的JavaScript可以做这样的事情:
var id;
var $body = $('body');
if(id = $body.data('job-id'))
// Do some job things.
else if(id = $body('user-id'))
// Do some user things.
and you'd still be HTML5 compliant and you wouldn't have to muck about with hidden inputs. 并且你仍然符合HTML5标准,你不必沉溺于隐藏的输入。
You don't have to use <body>
of course, your HTML probably has some top level container with a known id
so you could use that instead. 当然,您不必使用
<body>
,您的HTML可能有一些具有已知id
顶级容器,因此您可以使用它。
I'd suggest one of the following: 我建议以下之一:
As Jamsi suggested, include <%= params[:id] %>
or <%= @job[:id] %>
directly in your javascript: 正如Jamsi建议的那样,直接在您的javascript中包含
<%= params[:id] %>
或<%= @job[:id] %>
:
var id = <%= @job[:id] %>
If your javascript is in a separate file, follow Mu's advice. 如果您的javascript位于单独的文件中,请遵循Mu的建议。 Add the
<%= @job[:id] %>
to one of your view's html tags, and query it. 将
<%= @job[:id] %>
到您的一个视图的html标记中,然后进行查询。
不仅仅是<%= params [:id]%>吗?
Here is a complete example, combining from the answers already provided. 这是一个完整的例子,结合已经提供的答案。
Using the params[:id]
and the body element, the following inline statement will produce a data-params-id
attribute, that can be used generically in a layout file: 使用
params[:id]
和body元素,以下内联语句将生成data-params-id
属性,该属性可以在布局文件中一般使用:
<body <%= "data-params-id=#{params[:id]}" if params.has_key?(:id) %> >
This can then be accessed with the following: 然后可以使用以下方法访问它:
JavaScript: JavaScript的:
var dataId = document.body.getAttribute('data-params-id');
jQuery: jQuery的:
var dataId = $('body').data('params-id');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.