<HTML>
<HEAD>
<TITLE>表格动态追加、插入、删除行</TITLE>
</HEAD>
<BODY >
<table id="DetailTable" border="1" width="60%" align="center" cellpadding="2" cellspacing="0" bordercolor="#000000" bordercolordark="#ffffffff" >
<tr>
<td width="40%" align="center" bgcolor="#999999">姓名</td>
<td width="20%" align="center" bgcolor="#999999">性别</td>
<td width="40%" align="center" bgcolor="#999999">年龄</td>
</tr>
<tr>
<td width="40%" align="center"> <input type="text" name="username" style="width:200px"/></td>
<td width="20%" align="center">
<select style="width:100px">
<option value="boy">男</option>
<option value="girl">女</option>
</select>
</td>
<td width="40%" align="center"><input type="text" name="age" style="width:200px"/></td>
</tr>
</table>
<table id="TmpTable" style="display:none;">
<tr>
<td width="40%" align="center"><input name="msgid" type="radio" value="msgid"><input type="text" name="username" style="width:200px"/></td>
<td width="20%" align="center">
<select style="width:100px">
<option value="boy">男</option>
<option value="girl">女</option>
</select>
</td>
<td width="40%" align="center"><input type="text" name="age" style="width:200px"/></td>
</tr>
</table>
<br>
<table border="0" width="96%" align="center" >
<tr><td align="center">
<input type=button class="appButton" onClick="doAppend(DetailTable)" value=" 追 加 " >
<input type=button class="appButton" onClick="doInsert(DetailTable)" value=" 插 入 " >
<input type=button class="appButton" onClick="doRemove(DetailTable)" value=" 删 除 " >
</td>
</table>
<script language="javascript">
function doAppend(obj){
if(obj==null){
return;
}
rows=obj.rows;
if(rows==null){
return;
}
srcElem=rows[rows.length-1];
var tmpTable=TmpTable;
if(tmpTable==null){
return;
}
var trows=tmpTable.rows;
if(trows==null){
return;
}
newrow = obj.insertRow(srcElem.rowIndex+1);
temprow=trows[0].cloneNode(true);
newrow.replaceNode(temprow);
newrow=null;
tmprow=null;
}
function removeAllRow(obj){
if(obj==null){
return;
}
rows=obj.rows;
for(i=1;i<rows.length;i++){
desc=rows[i];
obj.deleteRow(desc.sectionRowIndex);
i--
rows=obj.rows;
}
}
function doInsert(obj){
var srcElem=getSelectedRow(obj);
if(srcElem==null){
alert("请选择要插入的行");
return;
}
var tmpTable=TmpTable;
if(tmpTable==null){
return;
}
var trows=tmpTable.rows;
if(trows==null){
return;
}
window.status="";
newrow = obj.insertRow(srcElem.rowIndex);
temprow=trows(0).cloneNode(true);
newrow.replaceNode(temprow);
window.status="";
}
function doRemove(obj){
srcElem=getSelectedRow(obj);
if(srcElem==null){
alert("请选则要删除的行");
return;
}
obj.deleteRow(srcElem.sectionRowIndex);
}
function getSelectedRow(obj){
if(obj==null){
return null;
}
rows=obj.rows;
if(rows==null){
return null;
}
var field=document.all.msgid;
if(field==null){
return null;
}
var srcElem=null;
for(i=0; i<field.length; i++){
if(field[i].checked){
srcElem=field[i];
break;
}
}
if(srcElem==null){
return null;
}
while (srcElem.tagName != "TR"){
srcElem = srcElem.parentElement;
}
return srcElem;
}
</script>
</BODY>
</HTML>