我有一个表单,我输入了学生信息(姓名、电子邮件、地址),并且在单击按钮后我能够使用 JS 添加一个新行(由三列组成)。每次创建新行时,都会创建三个新列,其中包含三个输入框,每个输入框都有自己的元素 ID。到现在为止还挺好。但是,现在我终生无法弄清楚如何删除添加的最后一行。下面是我的代码:
var student_ids = 0;
document.getElementById("studentCount").value = student_ids;
function anotherStudent(){
document.getElementById("student_info").innerHTML +=
"<div class='section colm colm4'>"+
"<input type='text' name='stud_name_" + student_ids + "'id='stud_name_" +student_ids+ "'class='gui-input' placeholder='Student name'>"+
"</div><!-- end section -->" +
"<div class='section colm colm4'>" +
"<input type='email' name='stud_email_" + student_ids + "'id='stud_email_" + student_ids + "'class='gui-input' placeholder='Email'>" +
"</div><!-- end section -->" +
"<div class='section colm colm4'>" +
"<input type='text' name='stud_address_" + student_ids + "'id='stud_address_" + student_ids + "'class='gui-input' placeholder='Address'>"+
"</div><!-- end section -->" ;
student_ids = ++student_ids;
document.getElementById("studentCount").value = student_ids ;
}
function removeStudent(){
var x = document.getElementById('stud_name_'+student_ids);
var y = document.getElementById('stud_email_'+student_ids);
var z = document.getElementById('stud_address_'+student_ids);
x.remove();
y.remove();
z.remove();
}
答案 0 :(得分:1)
编辑:
您没有删除 div,只是删除了输入本身。插入一行后,您还将增加 student_ids
全局变量。这意味着 removeStudent()
函数将始终尝试删除不存在的行。
最好将所需的 student_ids
传递给 removeStudent()
,或者手动减少该值。
在旧环境(例如资源管理器)中:
您不能直接从 JavaScript 中删除 DOM 元素。这有点不直观,但您必须转到该元素的父级并将其从那里删除:
var element = document.getElementById('stud_name_'+student_ids);
element.parentNode.removeChild(element);