最近在找一些关于动态表格方面的资料,经过小小组合后可以动态的增加行,及读取表格中的值,在脚本相对不好调试,所以就将我调好的代码放上来,可以直接运行看结果的
<html >
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312"/>
<title>动态添加删除表格</title>
<Script Language="Javascript">
var cGetRow=-99999;
function AddRow()
{
//添加一行
var i =tab1.rows.length;
var Nam="name"+i;
var Cod="code"+i;
var newTr = tab1.insertRow();
//添加两列
var newTd0 = newTr.insertCell();
var newTd1 = newTr.insertCell();
var newTd2 = newTr.insertCell();
var s='<input type="text" name='+Nam+' id='+ Nam +'>';
var t='<input type="text" name='+Cod+' id='+ Cod +'>';
//设置列内容和属性
newTd0.innerHTML = '<input type="checkbox" id="box4" onClick="GetRow()">';
newTd1.innerHTML= s;
newTd2.innerHTML= t;
}
function DelRow(iIndex)
{
//删除一行
if(iIndex==-99999)
alert("系统提示:没有选中行号!");
else
tab1.deleteRow(iIndex);
}
function GetRow()
{
//获得行索引
//两个parentElement分别是TD和TR哟,rowIndex是TR的属性
//this.parentElement.parentElement.rowIndex
cGetRow=window.event.srcElement.parentElement.parentElement.rowIndex;
}
function ReadRow()
{
alert(tab1.rows.length);
for(var i=0;i<tab1.rows.length;i++)
{
alert(document.getElementById("name"+i).value);
alert(document.getElementById("code"+i).value);
}
//显示行号
//alert(cGetRow);
//alert(document.getElementsByTagName("tr").length);
}
</script>
</head>
<body>
<table id="tab1" border=1>
<tr id="tr1">
<td width=6%><input type=checkbox id="box1" onClick="GetRow()"></td>
<td id="a"><input type=text name="name0" id="name0"></td>
<td><input type=text name="code0" id="code0"></td>
</tr>
</table>
<input type="submit" name="Submit" value="增加一行" οnclick="javascript:AddRow();">
<input type="submit" name="Submit" value="删除一行" οnclick="javascript:DelRow(cGetRow);">
<input type="submit" name="Submit" value="读取表格中的值" οnclick="javascript:ReadRow();">
</body>
</html>