在jquery中克隆后更改各种id [英] Changing various id's after cloning in jquery

查看:645
本文介绍了在jquery中克隆后更改各种id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试克隆表格行并更新多个ID以反映输入字段。我开始做这个并且它有效:

I'm trying to clone a table row and update the multiple id's to reflect the input fields. I start by doing this and it works:

$(id).clone().attr("id", "newId");

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

That changes the id of my main table row to the new id. In the table row I have other id's that need to be changed. For example:

<input type="text" id="input_1">

将更改为:

<input type="text" id="input_2">

我认为改变身份证会是这样的:

I thought it would be something like this to change the id's:

$(id).clone().attr("id", "newId").("#input_1").attr("id", "input_2");

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

This doesn't work. How can I fix this so that all of the id's change?

推荐答案

由于你错过了函数调用,程序会崩溃。

The program will crash as you have it since you're missing a function call.

请尝试这样做。请注意对的调用find()

Try this instead. Notice the call to find():

$(id).clone().attr("id", "newId").find("#input_1").attr("id", "input_2");

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

It will probably be better to reference the clone in a variable first.

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模式,你可能会做一些更自动化的事情。

You can set the ID attributes one at a time for the descendants of your clone if you wish. If there are several, and if you have a consistent pattern for IDs, you will likely be able to do something a little more automated.

编辑:

以下是示例自动更新<$ c $中的所有ID c> $ clone 。

请注意,这可能不适合您,因为它假定 全部 ID以数字结尾。

Please note that this may not work for you, as it assumes that all the IDs end with a number.

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);
});

这篇关于在jquery中克隆后更改各种id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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