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

Javascript 在JQuery中克隆时更改名称属性,javascript,jquery,html,Javascript,Jquery,Html,我有一张这样的表格 <tr id='actionRow'> <td> <input type="text" name='actionInput[0][action]' id="actionInput" placeholder='Action' class="form-control"/> </td> <td> <input type="text" name='actionI

我有一张这样的表格

<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>
更新克隆项的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代码,为什么replace不为我这样做


谢谢

看起来您假设中存在“i”。每个函数都不提供参数:

.each(function(i, elem){
....code
})
..而且,当您进行替换时,名称将完全相同。看起来您不应该替换“[”+(id-1)+“]”,而应该简单地替换为“[0]”

(对不起,我在打电话——这是完整的回答)主要问题是each(…)循环将tr的idx与输入的idx混淆(此外,无法保证克隆行的idx总是比新克隆行少一个)。您需要一个依赖于表中的行数而不是克隆行的索引的嵌套循环

下面是一个JSFIDLE:


对不起,我必须跳出来。当我使用按钮时,为什么这不起作用?嗨,尼克,更新了这个家伙的小提琴来显示按钮的用法@NickPrice-tr上的find(…)只查找输入元素,您需要添加其他类型:.find(“input,select,button”)--类似的内容。@NickPrice-抱歉,我误解了这个问题,请参阅JF的JSFIDDLE谢谢,最终解决了它。有一件事我搞不清楚,那就是删除按钮。如果没有I变量,我如何处理这个问题?
.each(function(i, elem){
....code
})
$("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");