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

Tri*_*rip 1 forms jquery 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>
Run Code Online (Sandbox Code Playgroud)

并用一个按钮复制它并增加变量号..

$(".add_another_button").click(function(){
    ...
};
Run Code Online (Sandbox Code Playgroud)

gna*_*arf 6

这样的东西?

$(".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');
});
Run Code Online (Sandbox Code Playgroud)