日期:2014-05-16 浏览次数:20349 次
<html>
??? <head>
?????? <title>动态增加删除行的实例</title>
?????? <script language="javascript">
????????? //使用clone方式来生成一行,targetTable是需要添加行的table的ID,sourceTable是clone对象
???????? //talbe的ID,即复制sourceTable的第一行插入到targetTable中,完成增加行的操作
???????? function insertRow(targetTable,sourceTable)
???????? {
?????????? var oTBODY???? = document.getElementById(targetTable).tBodies.item(0);
?????????? var oTBODYData = document.getElementById(sourceTable).tBodies.item(0);
?????????? var rowsCount = oTBODYData.rows.length;
?????????? for(var i=0;i<rowsCount;i++){
???????????? oTBODY.appendChild(oTBODYData.rows[i].cloneNode(true));
?????????? }
???????? }???
??????? function deleteRow(Field,targetTable){
????????????? var findex = getElementOrder(Field)-1;//此处减1是因sourceTable中有一行是隐藏的
????????????? document.getElementById(targetTable).deleteRow(findex);
???????? }??????????????
?????????? //? 查询出将要删除的行所在的位置index
?????????? function getElementOrder(field){
?????????????? var i = 0;
?????????????? var order = 0;
?????????????? var elements = document.getElementsByName(field.name);
?????????????? for(i=0;i<elements.length;i++){
?????????????????? order++;
?????????????????? if(elements[i]==field){
?????????????????????? break;
?????????????????? }
?????????????? }
?????????????? return order;
?????????? }
?????? </script>
??? </head>
??? <body>
<div><b>DIV中的动态表增加行</b></div><br>
<div style="height:200;width:400;overflow:auto;">
?????? <table id = "sourceTable" style="display:none;">
?????????? <tr>
????????????? <td><input type="button"? name = "deleteButton" value="删除" onclick="deleteRow(this,'targetTable')"></td>
????????????? <td><input type="text" name="username"></td>
????????????? <td><input type="password" name ="password"></td>
????????????? <td><input type = "text" name= "age"></td>
?????????? </tr>
?????? </table>
?????? <!--如果添加align="center"竟然会影响DIV的位置,而居左、居右都没影响。---table id="targetTable" width="100%" align="center">
?<table id="targetTable" width="100%">
?????????? <tr>
? <td> </td>
? <td>用户名</td>
? <td>密码</td>
? <td>年龄</td>????????????
?????????? </tr>
?????? </table>
</div>
??? </body>
<input type="button" value="增加行" onclick="insertRow('targetTable','sourceTable');">
</html>
?