簡體   English   中英

使用 vanilla js 從表單中刪除行

[英]Remove row from form with vanilla js

我有一個表格,我輸入學生信息(姓名,email,地址),我可以在單擊按鈕后使用 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();

}

編輯:

您沒有刪除 div,只是刪除了輸入本身。 插入一行后,您還將增加student_ids全局變量。 這意味着removeStudent() function 將始終嘗試刪除不存在的行。

最好將所需的student_ids傳遞給removeStudent() ,或者手動減小該值。

在舊環境(例如 Explorer)中:

您不能直接從 JavaScript 中刪除 DOM 元素。 這有點不直觀,但你必須 go 到該元素的父元素並從那里刪除它:

var element = document.getElementById('stud_name_'+student_ids);
element.parentNode.removeChild(element);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM