`

javascript 动态表格增加删除行

阅读更多
<table id="idTB" border=0>
  <tr id=idTR>
    <td>第一行 <input type='button'></td>
  </tr>
</table>
<input type="button" onclick="addRow()" value="添加一行"><br>
<input type="button" onclick="delRow()" value="删除一行"> Row index:
<input id="idIndex">(<a id="idFirst">1</a>~<a id="idLast">1</a>)

<script>
function addRow(){//添加表格的一行
  //alert(idTB.rows.length)
  oTR=idTB.insertRow(idTB.rows.length);
  tmpNum=oTR.rowIndex;
  // alert(tmpNum)
  oTD=oTR.insertCell(0);
  oTD.innerText="第" + tmpNum+"行";//在该处添加的HTML代码会原封不动的显示在页面上
  oTD.innerHTML="<input type='text' name='txt"+tmpNum+"'>";//要在该格添加的HTML代码填在这里,因为这里是text,注意不要重名了。
  idLast.innerText=idTB.rows.length;
  if(idTB.rows.length>0)
    idFirst.innerText='1';
  return true;
}
function delRow(){//删除表格的一行
  sIndex=idIndex.value;
 // alert(sIndex)
  if(sIndex=='')
    {
 sIndex=idTB.rows.length-1;
  alert(sIndex)
 }
  else
    sIndex=parseInt(sIndex)-1;
    
    idTB.deleteRow(sIndex);
  
    idLast.innerText=idTB.rows.length;

    if(idTB.rows.length==0)
       idFirst.innerText='0';
}
</script> 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics