如何在jquery中的.clone()上增加值 [英] How to increment values on .clone() in jquery

查看:115
本文介绍了如何在jquery中的.clone()上增加值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试克隆表单并将表单名称从(例如)#form更改为克隆到#form1时,并在输入上执行相同操作,而我真的对如何执行此操作感到困惑!由于我整天都在努力寻找解决方案,因此对您的任何帮助将不胜感激.这是我的代码:

I am trying to clone a form and change the form name from (for example) #form and when cloned to #form1 and do the same on the inputs and I am really stuck on how to do this! Any help would be GREATLY appreciated as I have spent ALL DAY trying to figure it out. Here is my code:

HTML:

<div class="avail">
<form action="submit.php" id="form1" method="post">
<input type="text" name="input1" />
<input type="text" name="anotherinput1" />
<input type="text" name="onemoreinput1" />
<input type="submit" name="submit1" value="submit" />
</form>
</div>

 <input type="submit" value="+" id="copy" />

JQUERY(用于克隆div和表单):

JQUERY (for cloning the div and form):

$("#copy").click(function(e) {
       $(".avail").clone().removeAttr('id').insertBefore(this);
       e.preventDefault();
    });

如果有人知道该怎么做,请给我很大的帮助!

Please if anyone knows how to do this, I would appreciate it soooo much!

推荐答案

您可以仅计算您拥有多少个可用对象,并将其用作新表单ID的运行计数.

You can just count how many avail objects you have and use that as the running count for the new form ID.

$("#copy").click(function(e) {
   var avails = $(".avail");
   var cnt = avails.length + 1;
   avails.eq(0).clone().insertBefore(this).find("form").attr("id", "form" + cnt);
   e.preventDefault();
});

您可以在这里看到它的工作: http://jsfiddle.net/jfriend00/9CU85/

You can see it work here: http://jsfiddle.net/jfriend00/9CU85/

如果还需要更新input元素的name属性上的数字,则可以使用以下代码执行此操作:

If you also need to update the numbers on the name attributes of the input elements, then you can use this code to do that also:

$("#copy").click(function(e) {
   var avails = $(".avail");
   var cnt = avails.length + 1;
   avails.eq(0).clone().insertBefore(this)
       .find("form").attr("id", "form" + cnt)
       .find("input").each(function() {
           this.name = this.name.replace(/\d+/, cnt);
       });
   e.preventDefault();
});​

您可以在这里看到此作品: http://jsfiddle.net/jfriend00/SKjMN/

You can see this one work here: http://jsfiddle.net/jfriend00/SKjMN/

这篇关于如何在jquery中的.clone()上增加值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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