代码之家  ›  专栏  ›  技术社区  ›  Trip

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

  •  1
  • Trip  · 技术社区  · 15 年前

    这看起来相对简单,我只是对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>
    

    然后用一个按钮复制并增加变量。。

    $(".add_another_button").click(function(){
        ...
    };
    
    2 回复  |  直到 15 年前
        1
  •  6
  •   gnarf    15 年前

    有点像 this ?

    $(".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');
    });
    
    推荐文章