0

我通过修改一点 Railscast 147 教程在 Rails 4 应用程序中设置了一个可排序的嵌套表单,一切正常。在我的项目中,每个都li包含fields_for一个嵌套资源的字段,包括一个复选框。我的问题是我想根据包含复选框的位置来处理复选框信息li。另外,如果其中一个输入被选中,这也会影响其他字段。我为此编写了一个 jquery 函数(主要是通过addClassand removeClass),并将对该函数的调用放在我的 sortable 和事件处理程序中。

  process_components = (o) ->
    $components = $(o).find('li')
    // other stuff
    $components.removeClass("parent_component child_component")
    $components.find('input.is_child').each ->
      firstcheck = $(this).prop('checked')
      secondcheck = $(this).closest('li').next().find('input.is_child').prop('checked')
      if firstcheck is true
        $(this).closest('li').addClass('child_component')
      if firstcheck is false and secondcheck is true
        $(this).closest('li').addClass('parent_component')

$('#components-list').sortable
    axis: 'y'
    items: "> li.component"
    update: ->
      $.post($(this).data('update-url'), $(this).sortable('serialize'))
      process_components $(this)

$('#components-list').on 'click', ':checkbox', (event) ->
    process_components '#components-list'

我的问题是,这只有在手动对列表元素进行几次排序后才能正常工作(元素只有在列表中的位置发生变化后才会响应复选框状态)。我在这里和谷歌上环顾四周,但我找不到任何关于为什么会发生这种情况的线索。它可能与 Jquery 和 Jquery UI 在处理方面的差异有关addClass吗?有想法该怎么解决这个吗?谢谢

4

1 回答 1

0

一天后,我想通了,实际上fields_for是罪魁祸首。我不知道为什么会发生这种情况,但是检查渲染页面中的各种元素,我发现:idRails 生成的隐藏字段没有被放置为li包含所有其他组件字段的子字段。相反,隐藏:id字段最初显示为li包含它的兄弟,因此process_components定位到 DOM 中的错误元素。在 sortable 中拖动不同li的 s 后,建立了正确的 DOM 结构并且一切正常。因此,解决方案是通过在字段中指定f.fields_for(:components, include_id: false)并显式包含来覆盖 Rails 的默认值。通过这种方式,页面加载时一切正常。<%= f.hidden_field :id %>fields_for

于 2013-11-08T18:49:16.967 回答