在很多web应用中,我们会遇到很多需要动态插入多行纪录的地方。比如,在人才网站上,我们填写简历的时候,我们要填写我们的项目经验,我们可以根据自己的实际情况动态的添加条数,这种不是以单独页面的形式添加,这种动态添加是在同一个页面下动态添加,最后再一起提交到服务器保存到数据库中。
本文,我将以一个类似的例子来做一个前台用Javascript动态添加数据项,后台保存到数据库的例子。
浏览器:IE.6.0
后台:ASP (VBScript )
前台:HTML + JavaScript
HTML代码:
JS代码:
/**//*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 = nTR.insertCell(); // Create new cell
ntd.id = TDs[0].id; // copy the TD's id to new cell. | Attention! The TDs's
//suffix must be appointed
ntd.innerHTML = TDs.innerHTML; // copy the value in ntd'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.deleteRow(i+targPos);
}
}
}
前台代码总结:
上面的代码有一个要注意的地方,那就是原始行