<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gbk" />
<title>无标题文档</title>
<script type="text/javascript">
//每一行的索引
var index = 3;
function btnAddRow(){
//创建新行的id
var rId = "tr" + index;
//随机数
var ranPrice = "¥" + Math.round((Math.random() * 100));
//table对象
var table1 = document.getElementById("table1");
//行数
var rowCount = table1.rows.length;
//添加到最后一行
var newRow = table1.insertRow(rowCount);
//添加ID
newRow.id = rId;
//给第一列添加
var newCell1 = newRow.insertCell(0);
//内容
newCell1.innerHTML = "西游记"+index;
//给第二列添加
var newCell2 = newRow.insertCell(1);
//内容
newCell2.innerHTML = ranPrice;
//给第三列添加
var newCell3 = newRow.insertCell(2);
//内容
newCell3.innerHTML = "<input type='button' name='button' id='button' value='删除' onclick='btnDelRow(\""+rId+"\")' />";
//alert(newCell3.innerHTML);
//变量++
index ++;
}
function btnUpdateRow(rowId){
//行对象
var delRow = document.getElementById(rowId);
//获取当前行的第1列的文本框
var items = delRow.cells[1].getElementsByTagName("input");
//获取当前文本框的值
var price = "¥"+items[0].value;
//修改当前行的第一列的文本
delRow.cells[1].innerHTML = price;
//修改当前行的第二列的文本
delRow.cells[2].innerHTML = "<input type='button' name='button' id='button' value='删除' onclick='btnDelRow(\""+rowId+"\")' /> <input type='button' value='修改' onclick='btnEditRow(\""+rowId+"\")'/>";
}
function btnEditRow(rowId){
//行对象
var delRow = document.getElementById(rowId);
//获取当前行的第1列的文本
var price = delRow.cells[1].innerHTML.substring(1);
//修改当前行的第1列
delRow.cells[1].innerHTML = "<input type='text' size='2' value='"+price+"'/>";
//修改当前行的第2列
delRow.cells[2].innerHTML = "<input type='button' name='button' id='button' value='删除' onclick='btnDelRow(\""+rowId+"\")' /> <input type='button' value='确定' onclick='btnUpdateRow(\""+rowId+"\")'/>";
}
function btnDelRow(rowId){
//行对象
var delRow = document.getElementById(rowId);
//行的数
var delRowIndex = delRow.rowIndex;
//表对象
var table1 = document.getElementById("table1");
//删除
table1.deleteRow(delRowIndex);
}
</script>
</head>
<body>
<table id="table1" width="500" border="1" cellspacing="1" cellpadding="1">
<tr id="tr0">
<td>书名</td>
<td>价格</td>
<td>操作</td>
</tr>
<tr id="tr1">
<td>三国演义</td>
<td>¥99</td>
<td>
<input type="button" name="button" id="button" value="删除" onclick="btnDelRow('tr1')" /> <input type="button" name="button" id="button" value="修改" onclick="btnEditRow('tr1')" />
</td>
</tr>
<tr id="tr2">
<td>水浒传</td>
<td>¥100</td>
<td><input type="button" name="button2" id="button2" value="删除" onclick="btnDelRow('tr2')" /></td>
</tr>
</table>
<p>
<input type="button" name="button3" id="button3" value="新增一行" onclick="btnAddRow()" />
</p>
</body>
</html>
http://blog.163.com/xiao_long/blog/static/21765117420132287164243/
【javascript】Dom操作 表格的添加行,删除行,修改行,
于 2013-07-25 14:46:16 首次发布