我正在尝试克隆表格行并更新多个 ID 以反射(reflect)输入字段。我首先这样做并且它有效:
$(id).clone().attr("id", "newId");
这会将我的主表行的 ID 更改为新的 ID。在表格行中,我还有其他需要更改的 ID。例如:
<input type="text" id="input_1">
将更改为:
<input type="text" id="input_2">
我认为更改 id 会是这样的:
$(id).clone().attr("id", "newId").("#input_1").attr("id", "input_2");
这行不通。我该如何解决这个问题,以便所有 id 都发生变化?
最佳答案
由于缺少函数调用,程序将崩溃。
试试这个。注意对 find()
的调用:
$(id).clone().attr("id", "newId").find("#input_1").attr("id", "input_2");
首先在变量中引用克隆可能会更好。
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");
如果您愿意,您可以一次为克隆的后代设置一个 ID 属性。如果有多个,并且您有一致的 ID 模式,您将可能能够做一些更自动化的事情。
编辑:
这是一个自动更新 $clone
中所有 ID 的示例。
请注意,这可能对您不起作用,因为它假定所有 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);
});
关于javascript - 在 jquery 中克隆后更改各种 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2977041/