JS控制网页动态生成任意行列数表格的方法

这是一个非常简单使用的JS在线生成表格的代码效果
通过JS功能代码,直接输入行数和列数就可以自动生成你需要的表格
当然你也可以扩展JS代码实现生成文字的各种形式

复制代码 代码如下:

<html>
<head>
<title>Js动态生成表格</title>
<style type="text/css">
table{font-size:14px;}
</style>
</head>
<body >
<script language="javascript">
function tableclick(name1,name2,name3){
  Trow=name1.value;
  Tcol=name2.value;
  Tv=name3.value;
  if ((Trow=="") || (Tcol=="") || (Tv=="")){
    alert("请将制作表格的条件填写完整");
  }
  else{
    r=parseInt(Trow);
 c=parseInt(Tcol);
 Table1(r,c,Tv);
  }
}
function tablevalue(a,ai,rows,col,str){
  int1=a.length;
  for (i=0;i<rows;++i){
 for (j=0;j<col;++j){
   if ((j==0)&&(ai>=int1)){break;}
   if (ai>=int1){
   str=str+"<td scope='col'>&nbsp;</td>";
   }
   else{
     if (j==0){
  str=str+"<tr><th scope='col'>&nbsp;"+(a[ai++])+"</th>";
     }
  else{
    if (j==col-1){
      str=str+"<td scope='col'>&nbsp;"+(a[ai++])+"</td>";
    }
    else{
     str=str+"<td scope='col'>&nbsp;"+(a[ai++])+"</td>";
    }
  }
   }
 }
 str=str+"</tr>";
  }
  return str;
}
function Table1(row,col,Str1){
var str="";
  a=new Array();
  s=new String(Str1);
  a=s.split("#");
  int1=a.length;
  ai=0;
  if (col<=int1){
   str=str+"<table>";
    for (i=0;i<col;++i){
   if (i==0){
    str=str+"<tr><th scope='col'>&nbsp;"+(a[ai++])+"</th>";
   }
   else{
     if (i==(col-1)){
    str=str+"<th scope='col'>&nbsp;"+(a[ai++])+"</th></tr>";
     }
     else{
    str=str+"<th scope='col'>&nbsp;"+(a[ai++])+"</th>";
     }
   }
 }
    if (int1>col){
      if (row>1){
  str=tablevalue(a,ai,row-1,col,str);
   }
 }
 str=str+ "</table>";
 aa.innerHTML=str;
  }
}
</script>
<form method="post" action="">
 <p><b>行数:</b>
    <input type="text" value="4">
    <b>列数:</b>
<input type="text" value="4">
<input type="button" value="生成表格"></p>
 <p><b>表值:</b></p>
 <p>
    <input wrap="VIRTUAL" value="COL1#COL2#COL3#COL4#ROW1#A1#A2#a3#ROW2#B1#B2#B3#ROW3#C1#C2#C3">
 </p>
</form>
<div></div>
</body>
</html>

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wgfzsj.html