在jquery中克隆后更改各种id

rsh*_*ers 10 javascript jquery

我正在尝试克隆表行并更新多个id以反映输入字段.我开始这样做,它的工作原理:

$(id).clone().attr("id", "newId");
Run Code Online (Sandbox Code Playgroud)

这会将我的主表行的id更改为新的id.在表格行中,我有其他需要更改的ID.例如:

<input type="text" id="input_1">
Run Code Online (Sandbox Code Playgroud)

将改为:

<input type="text" id="input_2">
Run Code Online (Sandbox Code Playgroud)

我认为改变id是这样的:

$(id).clone().attr("id", "newId").("#input_1").attr("id", "input_2");
Run Code Online (Sandbox Code Playgroud)

这不起作用.我怎样才能解决这个问题,以便所有id的变化?

use*_*716 29

因为你错过了一个函数调用,程序会崩溃.

试试这个.请注意以下呼叫find():

$(id).clone().attr("id", "newId").find("#input_1").attr("id", "input_2");
Run Code Online (Sandbox Code Playgroud)

首先在变量中引用克隆可能会更好.

var $clone = $(id).clone();

$clone.attr("id", "newId").find("#input_1").attr("id", "input_2");
$clone.find("#someElement").attr("id","someElement_2");
$clone.find("#someOtherElement").attr("id","someOtherElement_2");
Run Code Online (Sandbox Code Playgroud)

如果您愿意,可以为克隆的后代一次设置一个ID属性.如果有几个,如果您有一致的ID模式,您可能会做一些更自动化的事情.


编辑:

这是一个自动更新中所有ID 的示例$clone.

请注意,这可能对您不起作用,因为它假定所有 ID都以数字结尾.

var $clone = $(id).clone();    // Create your clone

      // Get the number at the end of the ID, increment it, and replace the old id
$clone.attr('id',$clone.attr('id').replace(/\d+$/, function(str) { return parseInt(str) + 1; }) ); 

     // Find all elements in $clone that have an ID, and iterate using each()
$clone.find('[id]').each(function() { 

     //Perform the same replace as above
    var $th = $(this);
    var newID = $th.attr('id').replace(/\d+$/, function(str) { return parseInt(str) + 1; });
    $th.attr('id', newID);
});
Run Code Online (Sandbox Code Playgroud)

  • @rshivers - 这就是我将克隆存储在变量中的原因.它存储了你克隆的整个结构,因此你可以对`$ clone`进行额外的`find()`调用.同样,如果你有几个要更新,可能有一种方法比一次更快地完成. (2认同)
  • 你可以改变`$ clone.attr('id',$ clone.attr('id').replace(/\d + $ /,function(str){return parseInt(str)+ 1;}));`to `$ clone.attr('id',function(i,attr){return attr.replace(/\d + $ /,function(str){return parseInt(str)+ 1;})});` (2认同)