我正在寻找一种简单有效的技术,可以使用JavaScript在html表中添加或删除行。 (没有使用jQuery)
答案 0 :(得分:4)
var theTable = document.getElementById("theTable");
theTable.deleteRow(0); //0 being first row.
答案 1 :(得分:0)
我一个月前写过这个......这不是最好的方式
<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>