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

jsGrid行展开表单动态ID事件绑定:rownumber自动递增方案咨询

解决jsGrid动态行表单元素的事件绑定问题

针对你在jsGrid动态行中绑定表单元素事件的需求,这里提供几种可靠的实现方式:

方法1:事件委托(推荐)

这种方式无需关心行号的递增逻辑,能自动适配动态生成的行(包括点击展开新增的行),避免重复绑定和闭包陷阱。

// 绑定到jsGrid的容器(替换为你的实际容器选择器,比如.jsGrid)
$(".jsGrid").on("input", "textarea[id^='comments-']", function() {
  // 从textarea的ID中提取行号
  const rownumber = $(this).attr("id").split("-")[1];
  const isCommentEmpty = $(this).val() === "";

  // 控制对应行的单选按钮状态
  $("#decision-" + rownumber + "-1").prop("checked", false);
  $("#decision-" + rownumber + "-2").prop("checked", !isCommentEmpty);
});

优势:

  • 只需绑定一次事件,后续新增的行自动生效
  • 无需维护行号循环逻辑,减少出错概率

方法2:基于行号循环绑定

如果需要针对已渲染的行逐个绑定事件,注意使用let声明循环变量(避免var的变量提升问题):

// 假设X是jsGrid的总行数
for (let rownumber = 1; rownumber <= X; rownumber++) {
  $("#comments-" + rownumber).on("input", function() {
    const isCommentEmpty = $(this).val() === "";

    $("#decision-" + rownumber + "-1").prop("checked", false);
    $("#decision-" + rownumber + "-2").prop("checked", !isCommentEmpty);
  });
}

如果必须使用var,需要通过闭包保存行号:

for (var rownumber = 1; rownumber <= X; rownumber++) {
  (function(currentRow) {
    $("#comments-" + currentRow).on("input", function() {
      const isCommentEmpty = $(this).val() === "";

      $("#decision-" + currentRow + "-1").prop("checked", false);
      $("#decision-" + currentRow + "-2").prop("checked", !isCommentEmpty);
    });
  })(rownumber);
}

方法3:依赖DOM结构(无需ID)

完全摆脱ID的限制,通过元素的层级关系定位目标控件,更健壮:

$(".jsGrid").on("input", "textarea[name='comments']", function() {
  const $form = $(this).closest("form");
  const isCommentEmpty = $(this).val() === "";

  // 通过表单和name属性找到对应单选按钮
  $form.find("input[name='decision'][value='N']").prop("checked", false);
  $form.find("input[name='decision'][value='Y']").prop("checked", !isCommentEmpty);
});

优势:

  • 不受ID命名规则变化影响
  • 代码更简洁,语义化更强

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 13:27:07