javascript - 在 jquery 中克隆后更改各种 id

标签 javascript jquery

我正在尝试克隆表格行并更新多个 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/

相关文章:

jquery - 想要延迟关闭 fancybox 窗口

javascript - mouseup 和 mousedown 在 jquery 中不能一起工作

javascript - 我可以在 Spidermonkey 中执行 Javascript 函数并获取返回值吗?

javascript - 获取 HTML5 DIV 或 CANVAS 元素同步转换更新的最有效方法是什么

javascript - 如何获取给定表单详细信息的嵌套 json 对象?

javascript - 2 个 CSS 类可以激活同一个脚本吗?

javascript - 输入谷歌地图方向

javascript - 组合 Javascript 函数

javascript - 将空格替换为逗号

javascript - 使用 ko :if binding knockout 绑定(bind)提供程序预处理器