日期:2014-05-16  浏览次数:20414 次

js批量创建带表单文本框的表格行和列
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>动态创建行</title>
<script>
     var id = 1;
function foundTable()
{
  for(var i=0;i<2;i++){ 
  var tableObj = document.getElementById("table2");
  var newTr = tableObj.insertRow();

  var newTd0 = newTr.insertCell();
  var newTd1 = newTr.insertCell();
  var newTd2 = newTr.insertCell();
  var newTd3 = newTr.insertCell();
 
  newTd0.innerText = ''+ id;
  newTd1.innerHTML = "<div align='center'><input id='cat"+id+"' type='text' size='12' value='cat"+id+"'/></div>";
  newTd2.innerHTML = "<div align='center'><select id='country"+id+"'><option value='中国'>中国</option><option value='美国'>美国</option></select></div>";
  newTd3.innerHTML = "<div align='center' ><input id='count"+id+"' type='text' size='12' value='count"+id+"'/></div>";
 
  id++;
  } 
}

function alertNeirong(){
  var tab = document.getElementById("table2");//获得表格对象(主要是表格内容)
  var tab_len = tab.rows.length;//获得表格的总行数
  var rows_innerText="";
 
  for(var i=1;i<tab_len;i++){
    rows_innerText = rows_innerText + tab.rows[i].cells[0].innerText+"  "+document.getElementById("cat"+(i)).value+"  "+document.getElementById("country"+i).value+"  "+document.getElementById("count"+(i)).value;
   rows_innerText = rows_innerText+";\n" ;  
  }
  alert(rows_innerText);
}
</script>
</head>
<body>
  <table align="center">
   <tr>
    <td><input type="button" value="批量创建" onclick="foundTable()"></td>
   <td>
    <input type="button" value="保存" onclick="alertNeirong()">
   </td>
   </tr>
  </table>
  <table border =1 align="center" id="table2">
   <tr>
   <th>Id号</th>
   <th>猫名</th>
      <th> 类型</th>
   <th> 数量</th>
   </tr>  
  </table>
</body>
</html>