Add and delete tables made with JS

There is no way to program design far away from the morning wind.- Jeffrey James

The purpose is to exercise the DOM.Write down the layout of the html first.

Full name:<input type="text"> Age:<input type="text"> Gender:<input type="text"> <input type="button" value="Add to">

Create a few basic pieces of information and start adding JS.

    var aInput = document.getElementsByTagName('input');           //Get Input on Page
    var len = aInput.length;                                       //Define a fixed number for the initial input, otherwise the following loops will be messy
    var oTable = document.getElementsByTagName('table')[0];        //Read the table of the page, [0] because getElementsByTagName gets the representation as an array
    aInput[aInput.length-1].onclick = function(){                 //Submitted Click Events
        var oTr = document.createElement('tr');                     //Create a tr node
        for(var i=0; i<len-1;i++){                                 //Start reading the value of input, -1 is to remove the Add button that follows
            var oTd = document.createElement('td');                 //Create a td node
            oTd.innerHTML = aInput[i].value;
            oTr.appendChild(oTd);                                   //Add a td to the end of a tr child element
        var oBtn = document.createElement('input');                 //This is where you add a delete button after each TR to delete the tr
        oBtn.type = 'button';
        oBtn.value = 'delete';
        oBtn.className = 'delBtn';
        oTable.appendChild(oTr);                                    //Add this tr to the table

        var oDelBtn = document.getElementsByClassName('delBtn');    //Extract deletions from tr
        for(var i=0; i<oDelBtn.length; i++) {                       //Make the delete button in each tr loop to
            oDelBtn[i].onclick = function () {                      //Add a click event to each tr's delete button
                oTable.removeChild(this.parentNode);                //Delete the parent of the button Delete tr

This is a simple add-delete function, but it's not the best way to do it, because creating a tr is a cycle that is not conducive to page optimization. You can use the bubbling nature of events to do this, which is just a small demo.(ps: Event delegation will be analyzed later)

Posted by DarkShadowWing on Tue, 07 Jan 2020 10:28:52 -0800