在 JQuery 中克隆时更改名称属性

Changing name attribute when cloned in JQuery

本文关键字:属性 JQuery      更新时间:2023-09-26

我有这样的表格

<tr id='actionRow'>
    <td>
        <input type="text" name='actionInput[0][action]' id="actionInput"  placeholder='Action' class="form-control"/>
    </td>
    <td>
        <input type="text" name='actionInput[0][deliveryDate]' id="dateInput" placeholder='Completion Date' class="form-control dateControl"/>
    </td>
</tr>

您可以看到我的输入名称是一个 2D 数组。 我为用户提供了向表中添加另一行的选项,这将克隆上述内容。 目前,我的代码是这样的

$("table tr").eq(1).clone().find("input").each(function() {
    $(this).closest('tr').attr('id', 'actionRow'+i);
    $(this).attr({
        'id': function(_, id) {
            return id + i
        },
        'name': function(_, id) {
            return  $(this).attr('name').replace('['+(id-1)+']', '['+id+']')
        },
        'value': ''
    });
    if ($(this).hasClass('dateControl')) {
        $(this).val("");
    }
}).end().appendTo("table");

我在更新克隆项目的 name 属性时遇到问题。对于第一个克隆的行,html 基本上应该如下所示

<tr id='actionRow'>
    <td>
        <input type="text" name='actionInput[1][action]' id="actionInput1"  placeholder='Action' class="form-control"/>
    </td>
    <td>
        <input type="text" name='actionInput[1][deliveryDate]' id="dateInput1" placeholder='Completion Date' class="form-control dateControl"/>
    </td>
</tr>

所以数组元素变成 1。 下一个克隆的行将有 2 个依此类推。

使用我提供的 JQuery 代码,为什么替换不为我执行此操作?

谢谢

看起来您假设 .each 函数中存在"i",但没有将其作为参数提供:

.each(function(i, elem){
....code
})

....此外,当您进行替换时,名称都将相同。 似乎您不应该替换"[" + (id-1) + "]",而应该简单地替换:"[0]"。

(对不起,我正在打电话 - 这是完整的回复) 主要问题是 each(...) 循环将 tr 的 idx 与输入的 idx 混淆(此外,不能保证克隆行的 idx 将始终比新的克隆行少 1)。 您需要一个嵌套循环,该循环依赖于表中的行数,而不是克隆行的索引。

这是一个jsFiddle:https://jsfiddle.net/5bzLeraz/

$("table tr").eq(0).clone().each(function(tr_idx, tr_elem) {
    var 
      $tr = $(tr_elem),
      newRowIdx = $("table tr").length;
    $tr.attr('id', 'actionRow' + newRowIdx);
    $tr.find("input").each(function(i_idx, i_elem) {
      var $input = $(i_elem);
      $input.attr({
          'id': function(_, id) {
              return id + newRowIdx;
          },
          'name': function(_, id) {
              return id.replace('[0]', '['+ newRowIdx +']');
          },
          'value': ''
      });
      if ($input.hasClass('dateControl')) {
          $input.val("");
      }
    });
  }).appendTo("table");