在jQuery中克隆表单并增加索引

在jQuery中克隆表单并增加索引,jquery,forms,cloneable,Jquery,Forms,Cloneable,这似乎相对简单,我只是被jQuery语法难住了 基本上我想采取以下形式: <div class="me_signup"> <input type="text" name="referral[0][name]" id="referral_0_name"> <br> <input type="text" name="referral[0][email]" id="referral_0_email"> </div> 什么样的 什

这似乎相对简单,我只是被jQuery语法难住了

基本上我想采取以下形式:

<div class="me_signup">
  <input type="text" name="referral[0][name]" id="referral_0_name">
  <br>
  <input type="text" name="referral[0][email]" id="referral_0_email">
</div>
什么样的

什么样的


您可以将所有html放在一个变量中,并使用.append()方法将其添加到特定的DOM元素中。而且,若您克隆了它,请确保将“id”更改为“class”,因为每个页面上的id必须是唯一的。

您可以将所有html放在一个变量中,并使用.append()方法将其添加到特定的DOM元素中。而且,若您克隆了它,请确保将“id”更改为“class”,因为每个页面上的id必须是唯一的。

你是天才。你的黄金版本在哪里?我知道我已经检查过了,但我还是被吹走了。我对你感激不尽。你对正则表达式的理解令人惊讶。你是天才。你的黄金版本在哪里?我知道我已经检查过了,但我还是被吹走了。我对你感激不尽。你对正则表达式的理解令人惊讶。
$(".add_another_button").click(function(){
    ...
};
$(".add_another_button").click(function() {
    var $newdiv = $(".me_signup:last").clone(true);
    $newdiv.find('input').each(function() {
        var $this = $(this);
        $this.attr('id', $this.attr('id').replace(/_(\d+)_/, function($0, $1) {
            return '_' + (+$1 + 1) + '_';
        }));
        $this.attr('name', $this.attr('name').replace(/\[(\d+)\]/, function($0, $1) {
            return '[' + (+$1 + 1) + ']';
        }));
        $this.val('');
    });
    $newdiv.insertAfter('.me_signup:last');
});