在应用程序的开发中,有些输入信息是动态的,比如我们要注册一个员工的工作经历,比如下图

如果做成死的,只能填写三个,如果是四个呢?或者更多呢,那不是添加不上去了吗,所以这样固然不好,我们可以用动态添加表格行实现,如下图,添加一行,输入一行信息,这样比较灵活

下面我们就来看看如何在asp和asp.net中结合javascript来实现这种效果:
首先,动态添加表格是要在前台实现的,当然后台也可以,不过可能要用到ajax,很麻烦,所以最好采用javascript来实现,下面来介绍动态添加表格行的两种方式:
第一种:源码
Javascript:
<script type="text/javascript">
/**//*This function is use to add one row dynamicly
* tabObj : Target table
* colNum: The number of columns that of a row in table
* sorPos: The source of the new row.
* targPos: The position where the new row will be added.
*
*/
function addRow(tabObj,colNum,sorPos,targPos){
var nTR = tabObj.insertRow(tabObj.rows.length-targPos); // Insert a new row into appointed table on the
//appointed position.
var TRs = tabObj.getElementsByTagName('TR'); // Get TRs collection from the appointed table
var sorTR = TRs[sorPos]; // Positioned the sorTR
var TDs = sorTR.getElementsByTagName('TD'); // Get TDs collection from the appointed row
if(colNum==0 || colNum==undefined || colNum==isNaN){
colNum=tabObj.rows[0].cells.length;
}
var ntd = new Array(); // Create a new TDs array
for(var i=0; i< colNum; i++){ // Traverl the TDs in row
ntd[i] = nTR.insertCell(); // Create new cell
ntd[i].id = TDs[0].id; // copy the TD's id to new cell. | Attention! The TDs's
//suffix must be appointed
ntd[i].innerHTML = TDs[i].innerHTML; // copy the value in ntd[i]'s innerHTML from corresponding TDs
}
}
/**//* This function is use to remove appointed row in appointed table
* tabObj: the appointed table
* targPos: target row position
* btnObj: currently clicked delete image button
*
*/
function deleteRow(tabObj,targPos,btnObj){ //Remove table row
for(var i =0; i<tabObj.rows.length;i++){
if(tabObj.getElementsByTagName('img')[i]==btnObj){
tabObj.deleteRow(i+targPos);
}
}
}
</script>
Html
<table id=tabUserInfo border=1 width="720">
<tr>
<td>姓名</td>
<td>性别</td>
<td>年龄</td>
<td>爱好</td>
<td>Delete</td>
</tr>
<tr style="display:none" id=trUserInfo>
<td id=tdUserInfo><input id=username name=username ></td>
<td id=tdUserInfo><input id=usersex name=usersex></td>
<td id=tdUserInfo><input id=userage name=userage></td>
<td id=tdUserInfo><input id=userlove name=userlove></td>
<td id=tdUserInfo>
<img alt="Delete" onClick="deleteRow(document.all.tabUserInfo,1,this)">
</td>
</tr>
<tr>
<td>
<input type=button value="Add" onClick="addRow(document.all.tabUserInfo,null,1,1)"></td>
</tr>
</table>
内容版权声明:除非注明,否则皆为本站原创文章。
