[英]How can I send an automatically generated ID for a form element to a javascript function?
我正在嘗試從Rails 3項目的表單頁面調用javascript函數。 我需要向函數發送特定元素的ID。 不幸的是,由於ID是由插件自動生成的,因此我無法輕松獲取ID。
我嘗試這樣做:
<%= t.select :number_type, @id_types, {}, {:onchange => "has_other_field(' + the_value.id.to_s + "');"} %>
<% if (!the_value.nil?) && (!the_value.number_type.nil?) && !@id_types_sm.include? the_value.number_type) %>
<script type="text/javascript">
setup_other_field("<%= the_value.number_type %>", ###ID WOULD GO HERE###);
</script>
<% end %>
..但是由於我不知道元素的ID,因此無法從函數中調用它。
因此,現在我嘗試通過輸入元素加載時從“ onload”調用函數來實現此目的:
<% if (!the_value.nil?) && (!the_value.number_type.nil?) && (!@id_types_sm.include? the_value.number_type) %>
<%# Call the function from the form helper only if the conditions are met %>
<%= t.select :number_type, @id_types, {}, {:onchange => "has_other_field(this.id);", :onload => "setup_other_field('" + the_value.number_type + "', this.id);"} %>
<% else %>
<%# Use the form helper without calling the function %>
<%= t.select :number_type, @id_types, {}, {:onchange => "has_other_field(this.id);"} %>
<% end %>
但是我意識到onload在這種情況下不起作用。 有什么解決方法嗎? 我怎么能
A)在第一個選項中從字段到函數獲取元素ID,或者
B)每當加載時從此輸入元素調用此函數?
...或C)另一種方法?
在此先感謝您,讓我知道更多詳細信息是否有幫助。
如果您在模型中保存了ID,請使用<%= model.id%>進行獲取。
此規則的例外是在創建對象時,即在將對象寫入數據庫之前。 如果您去編輯或其他任何地方都可以。
如果您將其放在頁面:/的某處,則可以使用jQuery為您獲取它。
<div id =“ id_of_the_element” attr_with_my_id =“ 15”> ABC </ div>
$("#id_of_the_element").attr('attr_with_my_id')
<輸入id =“ id_of_the_element ...> </輸入>
$("#id_of_the_element").value
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.