在JQuery中克隆并为每个添加唯一的ID [英] Clone in JQuery and adding unique IDs for each

查看:121
本文介绍了在JQuery中克隆并为每个添加唯一的ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个简单的网络应用程序,用户进来;从下拉框中选择并输入一些文本。一旦完成,用户按下一个生成按钮,它将显示结果连接字符串(显示在< span> )中,然后用户可以复制并粘贴。我已经有一行工作没有问题。

但我现在试图实现的是有一个添加行按钮,用户可以点击它来复制上面的行。我遇到的问题是确保一旦复制了该行并单击了生成按钮,复制的< span> 就会填充与先前< span>

更新:所以我设法使用JQuery中的 clone()函数来复制行和apend它在下面。是否可以更改每个被复制的元素的ID,包括表单的ID。也就是说,当它被复制时,被复制到的表单将被称为Form1。



JS我的小提琴在这里:



http://jsfiddle.net/XJEAn/



更新2:基本上我需要类似于这个,但为我试过的代码!

解决方案

我已经更新了你的小提琴,以便为新表单提供唯一的ID

http://jsfiddle.net/zq3AN/ b

可能并不完美,但应该让你的方向正确。


$(function(){
$('。addRow')。click(function(){
var copy = $(#original)。clone(true);
var formId ='NewForm'+ uniqueId;
copy.attr('id',formId);


$('#campaign')。append(copy) ;
$('#'+ formId).find('input,select')。each(function(){
$(this).attr('id',$(this).attr ('id')+ uniqueId);

));
uniqueId ++;
});
});

基本上,您复制表单,更改它的id,然后将其附加到div。然后你看看所有的输入,并选择和追加相同的uniqueId参数到他们的ID。


I'm creating a simple web app, where users come in; make a selection from drop down boxes and enter some text. Once this is completed, users press a "generate" button which will show them the resulting concatenated string (shown in a <span>), which users can then copy and paste. I've got it to work for one row no problem.

But what I am now trying to achieve is to have an "add row" button, which the user can click, that will replicate the row above. What I'm having trouble with is making sure that once the row is replicated and the generate button is clicked, the copied <span> will just populate the same values as the previous <span>.

UPDATE: So I've managed to use the clone() function from JQuery to copy the row and apend it underneath. Is it possible to change the ID's for each element that is copied, including the id of the form. i.e. so that when it's copied, the form that it's copied to will be called say, "Form1"

JS Fiddle of what I have is here:

http://jsfiddle.net/XJEAn/

UPDATE 2: Essentially I need something similar to this but for the code that I've tried!

解决方案

i've updated your fiddle to give the new forms unique id's

http://jsfiddle.net/zq3AN/

it's probably not exactly perfect, but should get you going in the right direction.

var uniqueId = 1;
$(function() {
     $('.addRow').click(function() {
         var copy = $("#original").clone(true);
         var formId = 'NewForm' + uniqueId;
         copy.attr('id', formId );


         $('#campaign').append(copy);
         $('#' + formId).find('input,select').each(function(){
            $(this).attr('id', $(this).attr('id') + uniqueId);

         });
         uniqueId++;  
     });
});

basically you copy the form, change it's id, and append it to the div. then you look form all the inputs and selects and append the same uniqueId parameter to their ids.

这篇关于在JQuery中克隆并为每个添加唯一的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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