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

发布于 2024-09-30 11:04:05 字数 391 浏览 1 评论 0原文

这看起来相对简单,我只是被 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(){
    ...
};

This seems relatively simple, I'm just stumped on jQuery syntax.

Basically I want to take this form :

<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>

And duplicate it with a button and increase the variable number..

$(".add_another_button").click(function(){
    ...
};

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

剧终人散尽 2024-10-07 11:04:05

这个之类的东西?

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

Something like 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');
});
我为君王 2024-10-07 11:04:05

您可以将所有 html 放入一个变量中,并使用 .append() 方法将其添加到特定的 DOM 元素。而且,如果您克隆它,请务必将“id”更改为“class”,因为 id 在每个页面上必须是唯一的。
官方文档中有关 .append() 的更多信息

You can put all that html in a variable, and use .append() method to add this to a particular DOM element. And, should you clone this, be sure to change "id" to "class", because id must be unique on each page.
Some more about .append() in official documentation

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文