jQuery appendTo只工作第一次,然后替换



我试图使用jQuery在表单的末尾添加克隆的div。下面是它的工作原理:

 var student_number = 1;
    var orig_student = $("#student-1").clone();
    $("#add-student-link").click(function() {
         ++student_number;
         orig_student.appendTo('form.reg').attr('id', 'student-' + (student_number)).addClass("additional-student");
    });

第一次效果很好,我得到一个div,看起来像这样:

<div id="student-2" class="additional-student"></div>

但是在那之后,div被替换为另一个id为"student-3"的div。Student-3应该是一个新的div,而不是替换student-2。什么好主意吗?

您只是在移动克隆而不是复制(请参阅您的问题下方的评论)。

$("#add-student-link").click(function() {
     ++student_number;
     $("#student-1").clone().attr('id', 'student-' + (student_number)).addClass("additional-student").appendTo('form.reg');
});

如果你克隆是为了保持副本的干净(可能是元素中的输入字段),那么克隆克隆。

var orig_student = $("#student-1").clone().attr('id','');
$("#add-student-link").click(function() {
     ++student_number;
     orig_student.clone().attr('id', 'student-' + (student_number)).addClass("additional-student").appendTo('form.reg');
});

当您第一次单击时,它可以工作,因为它使用克隆的div。

通过第二次单击,那么变量orig_student仍然引用相同的div,并且您再次追加它并更改类。

要使其工作,您需要创建另一个克隆以附加在函数内部。因为这是点击时要执行的。

var student_number = 1;
var orig_student = $("#student-1"); // No need to clone it here
$("#add-student-link").click(function() {
     ++student_number;
     // Create a new clone of your original div and append it
     // Like this we clone it only when really needed
     orig_student.clone().appendTo('form.reg').attr('id', 'student-' + (student_number)).addClass("additional-student");
});

最新更新