7、使用核心DOM方法创建表格
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<script type="text/javascript">
function createTable(){
var oTable=document.createElement("table");//创建表格元素
oTable.setAttribute("border", "1");//设置border属性为1
oTable.setAttribute("width", "100%");//设置width属性为100%
var oTBody=document.createElement("tbody"); //创建tbody元素
oTable.appendChild(oTBody);//添加tbody到oTable中
var oTr1=document.createElement("tr");
oTBody.appendChild(oTr1);
var oTD11=document.createElement("td");
oTD11.appendChild(document.createTextNode("一行一列"));
oTr1.appendChild(oTD11);
var oTD12=document.createElement("td");
oTD12.appendChild(document.createTextNode("一行二列"));
oTr1.appendChild(oTD12);
var oTr2=document.createElement("tr");
oTBody.appendChild(oTr2);
var oTD21=document.createElement("td");
oTD21.appendChild(document.createTextNode("二行一列"));
oTr2.appendChild(oTD21);
var oTD22=document.createElement("td");
oTD22.appendChild(document.createTextNode("二行二列"));
oTr2.appendChild(oTD22);
document.body.appendChild(oTable);//将表格添加到body中显示
}
</script>
</head>
<body οnlοad="createTable()">
</body>
</html>
显示效果如下:
采用HTML DOM创建表格,运用一些特性和方法:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<script type="text/javascript">
function createTable(){
var oTable=document.createElement("table");//创建表格元素
oTable.setAttribute("border", "1");//设置border属性为1
oTable.setAttribute("width", "100%");//设置width属性为100%
var oTBody=document.createElement("tbody"); //创建tbody元素
oTable.appendChild(oTBody);//添加tbody到oTable中
//创建第一行
oTBody.insertRow(0);//插入一个新行,为第一行
oTBody.rows[0].insertCell(0);//在该新行上插入第一个单元格
oTBody.rows[0].cells[0].appendChild(document.createTextNode("第一行第一列"));//在第一个单元格里添加文本内容
oTBody.rows[0].insertCell(1);//在该行上插入第二个单元格
oTBody.rows[0].cells[1].appendChild(document.createTextNode("第一行第二列"));//第二个单元格里添加文本
//创建第二行
oTBody.insertRow(1);//插入第二行
oTBody.rows[1].insertCell(0);//插入第二行第一个单元格
oTBody.rows[1].cells[0].appendChild(document.createTextNode("第二行第一列"));//添加文本到第一个单元格
oTBody.rows[1].insertCell(1);//插入第二行第二个单元格
oTBody.rows[1].cells[1].appendChild(document.createTextNode("第二行第二列"));//添加文本到第二个单元格
document.body.appendChild(oTable);//将表格添加到body中显示
}
</script>
</head>
<body οnlοad="createTable()">
</body>
</html>