如何在 jquery 中使用克隆复制表行并为控件创建新的唯一 ID

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3504499/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 15:33:55  来源:igfitidea点击:

How to Copy Table Row with clone in jquery and create new Unique Ids for the controls

jquery

提问by Nick Craver

How to Copy Table Row with clone in jquery and create new Unique Ids for the controls.Clone will acually copy data also .i don't want data to be copied .

如何在 jquery 中使用克隆复制表行并为控件创建新的唯一 ID。克隆也将复制数据。我不希望复制数据。

The table row contains the following information:

表行包含以下信息:

<tr> 
     <td><input type="text" id="txtTitle" name="txtTitle"></td> 
     <td><input type="text" id="txtLink" name="txtLink"></td> 
</tr> 

i need to create unique ids for all the new rows ,like txtTitle1, link1 ,Title2,link2 etc

我需要为所有新行创建唯一的 ID,如 txtTitle1、link1、Title2、link2 等

回答by Nick Craver

You could do something like this:

你可以这样做:

var i = 1;
$("button").click(function() ???{
  $("table tr:first").clone().find("input").each(function() {
    $(this).val('').attr('id', function(_, id) { return id + i });
  }).end().appendTo("table");
  i++;
})?;?

This would empty the values for new rows and give them unique IDs starting with txtTitle1, txtTile2, etc.

这将清空新行的值,并为它们提供以 txtTitle1、txtTile2 等开头的唯一 ID。

You ca give it a try here. If you needed to change the nametoo I'd pass an object to .attr()to keep it a bit cleaner, like this:

你可以在这里试一试。如果您也需要更改,name我会传递一个对象以.attr()使其更清晰,如下所示:

var i = 1;
$("button").click(function() {
  $("table tr:first").clone().find("input").each(function() {
    $(this).attr({
      'id': function(_, id) { return id + i },
      'name': function(_, name) { return name + i },
      'value': ''               
    });
  }).end().appendTo("table");
  i++;
});?

You can try that version out here.

您可以在此处试用该版本