选择标签jQuery更改检测在脚本中工作良好,而在带有CoffeeScript的Rails4.2.x项目中不工作

Select tag jQuery change detection working fine in script, not working in Rails 4.2.x project with CoffeeScript

本文关键字:工作 CoffeeScript 项目 Rails4 jQuery 标签 检测 选择 脚本      更新时间:2023-09-26

我们正试图在Rails 4.2项目的视图中使用jQuery/CoffeeScript来检测选择标记的更改。在我们的测试JSFiddle中,它运行良好。

然而,在我们的Rails视图中,按钮可以工作,但选择标记更改检测不起作用。我们的配置文件索引视图中有以下内容:

<%= form_for current_user.profile, :url => url_for(:controller => 'profile'), :method => :POST do |f| %>
    <div id="inf_profile_settings">
        <table id="tags-table" style="width:100%">
            <tr>
                <th>Name</th>
                <th>Lunches</th>
            </tr>
            <tbody id="tags-table-body" class="tags-table-body">
                <%= f.fields_for :tags do |tag| %>              
                    <%= render "tag_fields", :f => tag %>            
                <% end %>
                <div class="test_tags_button_container">
                    <%= button_tag "Test Tags", :id => "test-tags-button", :class => "test-tags-button", :type => "button", 'data-no-turbolink' => 'true' %>
                </div>
            </tbody>
        </table>
    </div>
<% end %> 

<%=render"tag_fields",:f=>tag%>代码与为每个表行加载的_tag_fields分部相关,这允许用户动态添加行。这是_tag_fields部分中的所有内容:

<tr class='nested-fields'>
    <td><%= f.select :inf_acct_id, @inf_names %></td>
    <td><%= f.select :lunches, @lunches1 %></td> 
</tr>

在profile.coffee中,我们有以下内容:

$(document).ready ->
    $("[id^='profile_attributes_'][id$='_inf_acct_id']").change(->
        alert "TestChange"
    )
    $(document).on 'click', '.test-tags-button', checkTestTagsButton

"checkTestTagsButton"函数只是一个警报,运行良好。选择标记更改检测也是一个警报,不起作用。

我们使用的框架自动生成分配给它从_tag_fields partial中呈现的选择标签的ID。如果你在Firebug中检查它们,它会分配这样的选择ID:

<select id="profile_tags_attributes_0_inf_acct_id" name="profile[tags_attributes][0][inf_acct_id]">
<select id="profile_tags_attributes_1_inf_acct_id" name="profile[tags_attributes][1][inf_acct_id]">

等等如图所示,框架根据行在select ID的中间插入一个整数,从0开始。这就是为什么我们使用字符串"[id^='profile_attributes_'][id$='_inf_acct_id']"来检测id以"profile_aattributes_"开头、以"inf_acct_id"结尾的选择标记中是否有任何更改,如另一篇文章中所述。

在上面发布的JSFiddle中,按钮和选择标记检测都可以正常工作,而在Rails视图中,只有按钮可以工作,原因我们根本无法确定。

如能在这一问题上提供任何协助,我们将不胜感激。

尝试

$ ->
  for el in $("[id^='profile_attributes_']")
    $(el).on 'change', (e) ->
      console.log e.currentTarget, 'changed'

也尝试将change替换为input