<html>
<head>
<title>JS内嵌表格</title>
<script type="text/javascript">
var gseq=1;
var gLastDetailImgObj=null;
//显示详细信息
function showDetailNumTable(){
var innerTR = "<table border=\"1\" align='center' width='100%'><tr style=\"background:gray;\"><td>inner11</td><td>inner12</td><td>inner13</td><td>inner14</td><td>inner15</td></tr><tr><td>inner21</td><td>inner22</td><td>inner23</td><td>inner24</td><td>inner25</td></tr><tr><td>inner31</td><td>inner32</td><td>inner33</td><td>inner34</td><td>inner35</td></tr><tr><td>inner41</td><td>inner42</td><td>inner43</td><td>inner44</td><td>inner45</td></tr></table>";
var imgObj=event.srcElement;
var tr=getOuterObj(imgObj,'TR'); // 得到tr对象
var newDivId=null;
if(!tr.newDivId){
var newTr=document.createElement("<TR></TR>"); // 创建tr
var newTd=document.createElement("td"); // 创建td
newTd.colspan=tr.children.length;
newDivId='detaildiv'+(gseq++); // 每一行内嵌的divID,每一行的ID都不同
var newDiv=document.createElement("<div id='"+newDivId+"'></div>"); // 创建div
newTr.appendChild(newTd); // tr中添加td
newTd.appendChild(document.createTextNode("各地区情况对比如下: "));
newDiv.innerHTML = innerTR; // 必须通过innerHTML方式添加内容,通过字符串拼进去的现实不出内容
newTd.appendChild(newDiv); // td中添加div
tr.parentNode.insertBefore(newTr,tr.nextSibling); // 必须通过tr的父节点才能用insertBefore,表示插入某个元素,这里表示在tr下个元素的前面(tr的后面)插入一行
tr.newDivId=newDivId; // 把新生成的div的ID赋给DIV
newTr.cells[0].colSpan= tr.children.length;
}
switchVisible(imgObj); // 控制展开还是合上内嵌表格
if(gLastDetailImgObj!=imgObj){
switchVisible(gLastDetailImgObj);
gLastDetailImgObj=imgObj;
}
else{
gLastDetailImgObj=null;
}
}
function switchVisible(imgObj){
if(!imgObj) return; // 如果imgObj对象为空,则返回
var tr=getOuterObj(imgObj,'TR');
var pvisible=('true'!=tr.currentVisibility);
tr.currentVisibility=(pvisible?'true':'false'); // pvisible为真时,tr.currentVisibility为true;pvisible为假时,tr.currentVisibility为false;
tr.nextSibling.style.display=(pvisible? '':'none'); // pvisible为真时,tr.nextSibling.style.display为'';pvisible为假时,tr.nextSibling.style.display为none;
}
//取得对象外围符合指定标签的第一个对象
function getOuterObj(obj,tagName){
while(obj!=null){
if(obj.tagName==tagName)
return obj;
obj=obj.parentNode;
}
return null;
}
</script>
</head>
<body>
<table border="1" align="center" width="80%">
<thead>
<tr style="background:GRAY;">
<th>姓名</th><th>年龄</th><th>电话</th><th>性别</th><th>住址</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td><td id = "no1"><a href="#" οnclick="showDetailNumTable('no1');">11111111</a></td><td>1</td><td>1</td><td>1</td>
</tr>
<tr>
<td>2</td><td id = "no2"><a href="#" οnclick="showDetailNumTable('no2');">22222222</a></td><td>2</td><td>2</td><td>2</td>
</tr>
<tr>
<td>3</td><td id = "no3"><a href="#" οnclick="showDetailNumTable('no3');">33333333</a></td><td>3</td><td>3</td><td>3</td>
</tr>
<tr>
<td>4</td><td id = "no4"><a href="#" οnclick="showDetailNumTable('no4');">44444444</a></td><td>4</td><td>4</td><td>4</td>
</tr>
</tbody>
</table>
</body>
</html>