如何知道 Rails 3 上 html 字段的 id?
阶段: 我正在使用嵌套模型,假设我们有两个模型:person
和 car
。 这里有 new.html.erb
页面:
<%= form_for(@person do |f| %>
...
<%= f.fields_for :cars do |car| %>
<div class="field">
<%= car.label :color %><br />
<%= car.text_field :color, :maxlength => 7 %>
</div>
<% end %>
...
<% end %>
将为每辆车生成此代码:
<form ...>
...
<div class="field">
<label for="person_cars_attributes_0_color">Car color</label><br />
<input id="person_cars_attributes_0_color"
name="person[cars_attributes][0][color]"
size="7" type="text" />
</div>
...
</form>
现在假设我们需要为每个输入字段添加一些 javascript 代码,以生成如下内容:
<script type="text/javascript">
$(document).ready( function() { $('#person_cars_attributes_0_color').mycolorpicker(); });
</script>
<input id="person_cars_attributes_0_color"
name="person[cars_attributes][0][color]"
size="7" type="text" />
注意,我们需要在 javascript 代码输入字段 id
中(在此示例中为 person_cars_attributes_0_color
)。
问题:我们如何获取每个生成的 html 字段的 id 值?
非常感谢您的帮助。 如果您需要更多详细信息,请随时向我询问。
Stage:
I am using nested models, supose we have two models: person
and car
.
And here you have new.html.erb
page:
<%= form_for(@person do |f| %>
...
<%= f.fields_for :cars do |car| %>
<div class="field">
<%= car.label :color %><br />
<%= car.text_field :color, :maxlength => 7 %>
</div>
<% end %>
...
<% end %>
This code will generate for each car:
<form ...>
...
<div class="field">
<label for="person_cars_attributes_0_color">Car color</label><br />
<input id="person_cars_attributes_0_color"
name="person[cars_attributes][0][color]"
size="7" type="text" />
</div>
...
</form>
Now suppose we need to put some javascript code for each input field, to generate something like this:
<script type="text/javascript">
$(document).ready( function() { $('#person_cars_attributes_0_color').mycolorpicker(); });
</script>
<input id="person_cars_attributes_0_color"
name="person[cars_attributes][0][color]"
size="7" type="text" />
Notice, we need in javascript code input field id
(in this example person_cars_attributes_0_color
).
Problem: How can we get this id value for each html field generated?
Thank you very much for your help.
Please feel free to ask me anything if you need more details.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如何为相关字段分配您事先确定的 ID 或类?
new.html.erb
:JavaScript:
How about assigning the field in question an ID or class that you determine before hand?
new.html.erb
:JavaScript:
我强烈建议您查看 Ryan Bates 的 nested_form gem。我认为它会满足您想做的一切。
I would highly recommend checking out the nested_form gem by Ryan Bates. I think it will take care of everything that you are looking to do.