开发者

How can I add/delete a table row using JavaScript?

开发者 https://www.devze.com 2023-01-03 22:33 出处:网络
I\'m looking for a simple, effective technique for adding or deleting a row in a html ta开发者_如何学Goble using JavaScript. (Without using jQuery)var theTable = document.getElementById(\"theTable\");

I'm looking for a simple, effective technique for adding or deleting a row in a html ta开发者_如何学Goble using JavaScript. (Without using jQuery)


var theTable = document.getElementById("theTable");
theTable.deleteRow(0);  //0 being first row.


I wrote this a month ago...Its not the best way

<html>
<head>
        <title>
                Crap work
        </title>
<script type="text/javascript">

function add_row()
{
        var table = document.getElementById('table');
        var rowCount = table.rows.length;
        var row = table.insertRow(rowCount);
        var cell1 = row.insertCell(0);
        var element1 = document.createElement("input");
        element1.type = "text";
        cell1.appendChild(element1);     
          var cell2 = row.insertCell(1);
        var element2 = document.createElement("input");
        element2.type = "text";
        cell2.appendChild(element2);
        var cell3 = row.insertCell(2);
        cell3.innerHTML = ' <span onClick="edit(this)">Edit</span>/<span onClick="delete_row(this)">Delete</span>';
        cell3.setAttribute("style", "display:none;");
        var cell4 = row.insertCell(3);
        cell4.innerHTML = '<span onClick="save(this)">Save</span>';
}


function save(e)
{
    var elTableCells = e.parentNode.parentNode.getElementsByTagName("td");
    elTableCells[0].innerHTML=elTableCells[0].firstChild.value;
    elTableCells[1].innerHTML=elTableCells[1].firstChild.value;
    elTableCells[2].setAttribute("style", "display:block;");
    elTableCells[3].setAttribute("style", "display:none;");
}
function edit(e)
{
    var elTableCells = e.parentNode.parentNode.getElementsByTagName("td");
    elTableCells[0].innerHTML='<input type="text" value="'+elTableCells[0].innerHTML+'">';
    elTableCells[1].innerHTML='<input type="text" value="'+elTableCells[1].innerHTML+'">';
    elTableCells[2].setAttribute("style", "display:none;");
    elTableCells[3].setAttribute("style", "display:block;");
}

function delete_row(e)
{
    e.parentNode.parentNode.parentNode.removeChild(e.parentNode.parentNode);
}
</script>
</head>
<body >
    <div id="display">
    <table id='table'>
        <tr id='id'>
            <td>
                Piemesons
            </td>

            <td>
                    23
            </td>   
            <td >
                <span onClick="edit(this)">Edit</span>/<span onClick="delete_row(this)">Delete</span>
            </td>   
            <td style="display:none;">
                <span onClick="save(this)">Save</span>
            </td>   
        </tr>   
    </table>    
        <input type="button" value="Add new row" onClick="add_row();" />
    </div>
</body> 
0

精彩评论

暂无评论...
验证码 换一张
取 消