<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>使用JavaScript动态添加删除表中一行</title>
<style type="text/css">
body, td{
font-size:12px;
}
hr
{
height:3px;
width:30px;
border-style:solid;
border-width:3px 0 0 0;
border-color:#FF0000;
}
</style>
<script type="text/javascript">
var tbl;
var index = 1;
function insert() {
tbl = document.getElementById("tblSample");
var i = index++;
var lastRow = tbl.rows.length;
var row = tbl.insertRow(lastRow);
row.align = "center";
// index cell
var tdIndex = document.createElement("td");
var elIndex = document.createTextNode(i);
tdIndex.appendChild(elIndex);
row.appendChild(tdIndex);
//color cell
var tdHR = document.createElement("td");
var elHR = document.createElement("hr");
tdHR.appendChild(elHR);
row.appendChild(tdHR);
// expression cell
var tdExp = document.createElement("td");
var elExp = document.createElement("input");
elExp.type = "text";
elExp.name = "txtExp" + i;
elExp.id = "txtExp" + i;
tdExp.appendChild(elExp);
row.appendChild(tdExp);
// place cell
var tdPlace = document.createElement("td");
var elLeft;
var elRight;
if (navigator.appName.indexOf("Explorer") > -1) {
var placeName = "place" + i;
elLeft = document.createElement("<input name=" + placeName + " checked=checked>");
elRight = document.createElement("<input name=" + placeName + ">");
}
else {
elLeft = document.createElement("input");
elLeft.checked = true;
elRight = document.createElement("input");
}
elLeft.type = "radio";
elLeft.name = "place" + i;
elLeft.value = "left";
elRight.type = "radio";
elRight.name = "place" + i;
elRight.value = "right";
tdPlace.appendChild(elLeft);
var elText = document.createTextNode("/");
tdPlace.appendChild(elText);
tdPlace.appendChild(elRight);
row.appendChild(tdPlace);
//delete cell
var tdDelete = document.createElement("td");
var elDelete = document.createElement("input");
elDelete.type = "button";
elDelete.id = "btnDelete" + i;
elDelete.value = "Delete";
elDelete.onclick = function() {
tbl.deleteRow(this.parentNode.parentNode.rowIndex);
}
tdDelete.appendChild(elDelete);
row.appendChild(tdDelete);
}
function removeRow(index) {
tbl.deleteRow(index);
}
</script>
</head>
<body>
<input type="button" value="Add" onclick="insert();" />
<table id="tblSample">
<thead>
<tr>
<th width="40">序号</th>
<th width="40">颜色</th>
<th width="150">表达式</th>
<th width="50">左/右</th>
<th width="60"></th>
</tr>
</thead>
</table>
</body>
</html>