动态表格 添加行 删除行 删除列

时间:2022-12-08 15:55:55

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
   
    <title>My JSP 'testtable.jsp' starting page</title>
   
 <meta http-equiv="pragma" content="no-cache">
 <meta http-equiv="cache-control" content="no-cache">
 <meta http-equiv="expires" content="0">   
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 <meta http-equiv="description" content="This is my page">
 <!--
 <link rel="stylesheet" type="text/css" href="styles.css">
 -->
 <script type="text/javascript">
  var strid="1";
  function addTableTr(){
   var oTr = document.getElementById("testtable").insertRow();
   var temp_trid="tr"+strid;
   oTr["id"]=temp_trid;
   var aText = new Array();
   var a1="AAA"+strid;
   var a2="BBB"+strid;
   var a3="CCC"+strid;
   var a4="DDD"+strid;
   var a5="<input type='button' name='deltr+"+i+"' trid='"+strid+"' value='删除' onclick=delTableRr('"+temp_trid+"')>";
   aText[0]=document.createTextNode(a1);
   aText[1]=document.createTextNode(a2);
   aText[2]=document.createTextNode(a3);
   aText[3]=document.createTextNode(a4);
   aText[4]=document.createElement(a5);
   strid++;
   for(var i=0;i<aText.length;i++){
    var oTd = oTr.insertCell(i);
    oTd.appendChild(aText[i]);
   }
   
   var str="";

   for(var tb in oTr){
    str=str+"oTr["+tb+"]="+oTr[tb]+"<br />";
   }
   abc.innerHTML=str;
  }
  
  function delTableRr(strid){
   var oTb = document.getElementById("testtable");
   var j=-1;
   for(var i=1;i<oTb.rows.length;i++){
    if(strid==oTb.rows[i]["id"]){
     j=i;
     break;
    }
   }
   if(oTb.rows.length>1 && j!=-1){
    if(confirm("你确认要删除吗")){
     oTb.deleteRow(j);
    }
   }
  }
  function deleteTableCell(strCell){
   var oTb = document.getElementById("testtable");
   var cellslen=oTb.rows[0].cells.length;
   var rowslen=oTb.rows.length;

   if(cellslen>0 && rowslen>0){
     for(var i=0;i<rowslen;i++){
      oTb.rows[i].deleteCell(strCell);
     }
   }
  }
 </script>
  </head>
 
  <body>
    <table id="testtable">
     <tr id="tr1">
      <th>第一列</th>
      <th>第二列</th>
      <th>第三列</th>
      <th>第四列</th>
      <th>第五列</th>
     </tr>
    </table>
    <input type="button" name="bt" value="添加一行" onclick="addTableTr();" />
    <input type="button" name="bt" value="删除一行" onclick="delTableRr();" />
   <input type="button" name="bt" value="删除一列" onclick="deleteTableCell(4);" />
   
   <div id="abc"></div>
  </body>
</html>