You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JQuery无法控制Rails+Cocoon动态表单中复选框最近div的显隐问题

解决方案

问题原因

  • 原代码使用全局类选择器$(".finished_year")、$(".expected_finished_time"),会匹配页面所有符合条件的元素,导致操作同步作用到所有教育经历表单块
  • closest()方法仅向上查找当前元素的祖先节点,.finished_year不属于复选框的祖先元素链,因此无法匹配到目标元素
  • 直接绑定change事件到.checkbox类,Cocoon动态新增的教育经历表单中的复选框不会触发该事件

修正后的JS代码

把原有script标签内的代码替换为以下内容即可:

$(document).ready(function() {
  // 事件委托绑定复选框变更事件,兼容动态新增的表单块
  $(document).on('change', '.checkbox', function() {
    // 定位当前复选框所属的单个教育经历表单容器
    const $currentForm = $(this).closest('.nested-fields');
    // 仅在当前表单容器内查找目标元素
    const $finishedYear = $currentForm.find('.finished_year');
    const $expectedTime = $currentForm.find('.expected_finished_time');

    if (this.checked) {
      $expectedTime.hide();
      $finishedYear.show();
    } else {
      $expectedTime.show();
      $finishedYear.hide();
    }
  });

  // 初始化所有表单块的显示状态,匹配默认选中逻辑
  $('.checkbox').each(function() {
    const $currentForm = $(this).closest('.nested-fields');
    if (this.checked) {
      $currentForm.find('.expected_finished_time').hide();
      $currentForm.find('.finished_year').show();
    } else {
      $currentForm.find('.expected_finished_time').show();
      $currentForm.find('.finished_year').hide();
    }
  });
});

实现逻辑说明

  • 所有查找操作都限制在当前触发事件的复选框所属的.nested-fields容器内,不会影响其他教育经历表单块
  • 采用事件委托的方式绑定事件,Cocoon动态新增的表单块中的复选框也能正常触发交互逻辑
  • 初始化阶段遍历所有已存在的复选框,根据自身选中状态设置对应区域的显示隐藏,符合默认复选框选中的需求

内容的提问来源于stack exchange,提问作者r3b00t

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 15:24:03