复制表行并增加所有名称属性 [英] Copy table row and increment all name attributes

查看:52
本文介绍了复制表行并增加所有名称属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们有一个这样的表:

Let's have a table like this:

<table>
 <tr>
  <td><input type="text" name="FirstName1" /></td>
  <td><input type="text" name="LastName1" /></td>
 </tr>
 <tr>
  <td><input type="text" name="FirstName2" /></td>
  <td><input type="text" name="LastName2" /></td>
 </tr>
</table>

我想要一个按钮,该按钮将在表的末尾添加具有增加的名称属性的新行,因此它将如下所示:

I want to have a button that will add new row at the end of the table with incremented name attributes so it will look like this:

<table>
 <tr>
  <td><input type="text" name="FirstName1" /></td>
  <td><input type="text" name="LastName1" /></td>
 </tr>
 <tr>
  <td><input type="text" name="FirstName2" /></td>
  <td><input type="text" name="LastName2" /></td>
 </tr>
 <tr>
  <td><input type="text" name="FirstName3" /></td>
  <td><input type="text" name="LastName3" /></td>
 </tr>
</table>

以此类推.

到目前为止,我有这个功能,但是它不会增加名称属性:

So far I have this but it does not increment name attributes:

$("#newRowButton").click(function(){
  $("table tr:last").clone().appendTo("table");
});

推荐答案

$("#newRowButton").click(function() {
  $("table tr:last")
      .clone()
      .appendTo("table")
      .find(':input')
      .attr('name', function(index, name) {
          return name.replace(/(\d+)$/, function(fullMatch, n) {
              return Number(n) + 1;
          });
      })
});

实时演示.

这篇关于复制表行并增加所有名称属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆