繁体   English   中英

如何将表单元素的自动生成的ID发送到javascript函数?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM