階段: 我使用的是嵌套模型,因此我們有兩個模型:person
和car
。 在這裏你有new.html.erb
頁:如何知道Rails 3上html字段的id?
<%= 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值?
非常感謝您的幫助。 如果您需要更多詳細信息,請隨時問我任何問題。
It太容易了,非常感謝,我在JavaScript和jQuery世界裏也很喜歡這裏。 – Israel