在JavaScript中动态删除行

时间:2014-09-15 22:41:47

标签: javascript html forms dom

我正在做一个表单(一个简单的WEB表单,基于Tom Negrino,JavaScript 8和w3Schools的脚本),用户按下Submit按钮,表单中的一些字段显示在一个表单中表格下的表格。

这是结果

Form

现在,我想删除该行,但只删除用户想要删除的行,点击相应的行。

这是我的JavaScript

window.onload = initForms;

function initForms() {
    for (var i=0; i< document.forms.length; i++) {
        document.forms[i].onsubmit = validForm;
    }
    document.getElementById("sunroof").onclick = doorSet;

    document.getElementById("estado").selectedIndex = 0;
    document.getElementById("estado").onchange = populateDays;

    /***********/
    //document.getElementsByTagName("form")[0].onsubmit = addNode;
    /***********/

    document.getElementById("env").onclick = function() {
        myFunction()
    };

}

function validForm() {
    var allGood = true;
    var allTags = document.getElementsByTagName("*");

    for (var i=0; i<allTags.length; i++) {
        if (!validTag(allTags[i])) {
            allGood = false;
        }
    }
    return allGood;

    function validTag(thisTag) {
        var outClass = "";
        var allClasses = thisTag.className.split(" ");

        for (var j=0; j<allClasses.length; j++) {
            outClass += validBasedOnClass(allClasses[j]) + " ";
        }

        thisTag.className = outClass;

        if (outClass.indexOf("invalid") > -1) {
            invalidLabel(thisTag.parentNode);
            thisTag.focus();
            if (thisTag.nodeName == "INPUT") {
                thisTag.select();
            }
            return false;
        }
        return true;

        function validBasedOnClass(thisClass) {
            var classBack = "";

            switch(thisClass) {
                case "":
                case "invalid":
                    break;
                case "reqd":
                    if (allGood && thisTag.value == "") {
                        classBack = "invalid ";
                    }
                    classBack += thisClass;
                    break;
                case "radio":
                    if (allGood && !radioPicked(thisTag.name)) {
                        classBack = "invalid ";
                    }
                    classBack += thisClass;
                    break;
                case "email":
                    if (allGood && !validEmail(thisTag.value)) classBack = "invalid ";
                    break;
                case "isNum":
                case "isZip":
                    classBack += thisClass;
                    break;
                default:
                    if (allGood && !crossCheck(thisTag,thisClass)) {
                        classBack = "invalid ";
                    }
                    classBack += thisClass;
            }
            return classBack;
        }

        function crossCheck(inTag,otherFieldID) {
            if (!document.getElementById(otherFieldID)) {
                return false;
            }
            return (inTag.value != "" || document.getElementById(otherFieldID).value != "");
        }

        function validEmail(email) {
            var re = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;

            return re.test(email);
        }

        function radioPicked(radioName) {
            var radioSet = "";

            for (var k=0; k<document.forms.length; k++) {
                if (!radioSet) {
                    radioSet = document.forms[k][radioName];
                }
            }
            if (!radioSet) {
                return false;
            }
            for (k=0; k<radioSet.length; k++) {
                if (radioSet[k].checked) {
                    return true;
                }
            }
            return false;
        }

        /****Veamos si esto funciona****/

        /*function checkboxPicked(checkboxName) {
            var checkboxSet = "";

            for (var k = 0; k < document.forms.length; k++) {
                if (!checkboxSet) {
                    checkboxSet = document.forms[k][checkboxName];
                }
            }
            if (!checkboxSet) {
                return false;
            }
            for ( k = 0; k < checkboxSet.length; k++) {
                if (checkboxSet[k].checked) {
                    return true;
                }
            }
            return false;
        }*/

        /*****************************************/

        function invalidLabel(parentTag) {
            if (parentTag.nodeName == "LABEL") {
                parentTag.className += " invalid";
            }
        }
    }
}

function populateDays() {
    var tamps = new Array("Ikon Hatch", "Fiesta", "Focus", "Mustang");
    var nvoleon = new Array("Aveo", "Spark");
    var slp = new Array("Gol", "CrossFox", "Clasico", "Jetta");

    var estado = document.getElementById("estado");
    var estadoStr = estado.options[estado.selectedIndex].value;

    if (estadoStr != "") {
        var valueEst = parseInt(estadoStr);
        document.getElementById("ciudad").options.length = 0;

        if (valueEst == 0) {
            for (var i = 0; i < tamps.length; i++) {
                document.getElementById("ciudad").options[i] = new Option(tamps[i]);
            }
        } else if (valueEst == 1) {
            for (var i = 0; i < nvoleon.length; i++) {
                document.getElementById("ciudad").options[i] = new Option(nvoleon[i]);
            }
        } else if (valueEst == 2) {
            for (var i = 0; i < slp.length; i++) {
                document.getElementById("ciudad").options[i] = new Option(slp[i]);
            }
        }
    } else {
        document.getElementById("ciudad").options.length = 0;
        document.getElementById("ciudad").options[0] = new Option("Model");
    }
}

function doorSet() {
    if (this.checked) {
        document.getElementById("twoDoor").checked = true;
    }
}

/*****************************/

/*function addNode() {
    var inText = document.getElementById("estado").value;
    var inText1 = document.getElementById("ciudad").value;

    var newText = document.createTextNode(inText);
    var newText1 = document.createTextNode(inText1);

    var newGraf = document.createElement("table");
    newGraf.appendChild(newText);
    newGraf.appendChild(newText1);

    var docBody = document.getElementsByTagName("body")[0];
    docBody.appendChild(newGraf);

    return false;
}*/

function myFunction() {
    var table = document.getElementById("myTable");

    var email= document.getElementById("emailAddr").value;
    var brand=document.getElementById("estado").value;
    var model=document.getElementById("ciudad").value;

    var row = table.insertRow(1);
    var cell1 = row.insertCell(0);
    var cell2 = row.insertCell(1);
    var cell3 = row.insertCell(2);
    cell1.innerHTML = email;
    cell2.innerHTML = model;
    cell3.innerHTML = brand;
}

我的HTML

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Formulario</title>
        <link rel="stylesheet" href="css/script06.css">
        <link rel="stylesheet" href="css/normalize.css">
        <link rel="stylesheet" href="css/bootstrap-3.2.0-dist/css/bootstrap.min.css">
        <link rel="stylesheet" href="css/bootstrap-3.2.0-dist/css/bootstrap-theme.min.css">
        <!--No se te olvide el css-->
        <!--<link rel="stylesheet" href="css/bootstrap-3.2.0-dist/css/bootstrap.min.css">
        <link rel="stylesheet" href="css/bootstrap-3.2.0-dist/css/bootstrap-theme.min.css">-->
        <script src="js/script08.js"></script>
        <!--No se te olvide el js-->
    </head>

    <body>
        <header></header>
        <main>
            <article>
                <p>
                    <h1>Choose your car</h1>
                </p>
            </article>
            <form action="#">
                <p>
                    <label for="emailAddr">Email Address:
                        <input id="emailAddr" type="text" size="40" class="reqd email">
                    </label>
                </p>
                <p>
                    <label for="passwd1">Password:
                        <input type="password" id="passwd1" class="reqd">
                    </label>
                </p>
                <p>
                    <label for="passwd2">Repeat Pass:
                        <input type="password" id="passwd2" class="reqd passwd1">
                    </label>
                </p>
                <!--<p>
                <label for="color">Colors:
                <select id="color" class="reqd">
                <option value="" selected>Choose a color</option>
                <option value="Red">Red</option>
                <option value="Green">Green</option>
                <option value="Blue">Blue</option>
                </select> </label>
                </p>-->
                <p>
                    Options: <label for="sunroof">
                        <input type="checkbox" id="sunroof" value="Yes">
                        Sunroof (Two door only)</label>
                    <label for="pWindows">
                        <input type="checkbox" id="pWindows" value="Yes">
                        Power Windows</label>
                </p>
                <p>
                    Doors: <label for="DoorCt"><!--Doors:&nbsp;&nbsp;-->
                        <input type="radio" id="twoDoor" name="DoorCt" value="twoDoor" class="radio">
                        Two</label>
                        <label for="DoorCt">
                        <input type="radio" id="fourDoor" name="DoorCt" value="fourDoor" class="radio">
                        Four </label>
                </p>
                <p>
                    <label>Brand:</label>
                    <select id="estado" class="reqd">
                        <option value="">Brand</option>
                        <option value="0">Ford</option>
                        <option value="1">Chevrolet</option>
                        <option value="2">Volkswagen</option>
                    </select>
                    &nbsp;
                    <select id="ciudad" class="reqd">
                        <option>Model</option>
                    </select>
                </p>
                <p>
                    <input type="submit" value="Enviar" id="env">
                    &nbsp;
                    <input type="reset">
                </p>
            </form>

            <br />

            <!--Veamos si funciona-->
            <table id="myTable">
                <tr>
                    <td>Email</td>
                    <td>Model</td>
                    <td>ID Brand</td>
                </tr>
                <tr>
                </tr>
            </table>

        </main>
        <footer></footer>
    </body>
</html>

我尝试在JavaScript中添加和添加额外的单元格:

cell4.innerHTML = <button onclick="myDeleteFunction()">Del</button>;

调用函数

function myDeleteFunction() {
    document.getElementById("myTable").deleteRow();
}

删除到行,但它没有工作。

我会感激任何帮助。感谢。

2 个答案:

答案 0 :(得分:1)

var node = nodes[0];
if (univArray[z].ownership != "public") {
    node.parentNode.removeChild(node)
}

答案 1 :(得分:0)

如果要根据对该行的单击删除表格行,可以使用以下内容:

<tr onclick="this.parentNode.removeChild(this)">

如果你想根据行中的按钮这样做,那么:

<tr>
  <td><button onclick="deleteRow(this)">Delete this row</button>

然后 deleteRow 功能是:

function deleteRow(element) {
  var row = upTo(element, 'tr');
  if (row) row.parentNode.removeChild(row);
}

辅助函数

// Return first ancestor of el with tagName
// or undefined if not found
function upTo(el, tagName) {
  tagName = tagName.toLowerCase();

  while (el && el.parentNode) {
    el = el.parentNode;
    if (el.tagName && el.tagName.toLowerCase() == tagName) {
      return el;
    }
  }

  // Many DOM methods return null if they don't
  // find the element they are searching for
  // It would be OK to omit the following and just
  // return undefined
  return null;
}

deleteRow 函数可以放在行内的任何位置,行可以放在任何类型的表格部分元素(头部,主体或脚部)中。您需要做的就是传递对行内任何元素的引用(按钮,复选框,单元格等)。

table.deleteRow 方法的问题在于,您必须知道要调用方法的元素中的行索引。行有一个 rowIndex 属性,它们是它们所在表中的索引,因此您必须使用该表(即row.parentNode.parentNode),而使用{{3方法并不要求你计算表格中行的位置,或者甚至知道父亲是头部,身体还是脚部分。

修改

要动态添加侦听器,您可以稍微修改该功能,并将类添加到将删除行的按钮,例如。

<!-- Sample markup -->
<table>
  <tr>
    <td><input type="button" class="rowDeleter" value="Delete Row">
  <tr>
    <td><input type="button" class="rowDeleter" value="Delete Row">
  <tr>
    <td><input type="button" class="rowDeleter" value="Delete Row">
</table>

添加类意味着您可以轻松识别要添加侦听器的元素。

<script>
window.onload = function() {

  // querySelectorAll and addEventListener require IE 8 or higher, use some other
  // method if support for older browsers is required
  var els = document.querySelectorAll('.rowDeleter');

  for (var i=0, iLen=els.length; i<iLen; i++) {
    els[i].addEventListener('click', deleteRow, false);
  }
}

// When attached using addEventListener, this in the function
// will be the element that called the listener    
function deleteRow() {
  var row = upTo(this, 'tr');
  if (row) row.parentNode.removeChild(row);
}

// Previously shown helper
function upTo(el, tagName) {
  tagName = tagName.toLowerCase();

  while (el && el.parentNode) {
    el = el.parentNode;
    if (el.tagName && el.tagName.toLowerCase() == tagName) {
      return el;
    }
  }
  return null;
}

</script>