前几天测试一个小程序,其中需要获取表格中某行第一个单元格自定义的属性值,很自然地就用到:
tr.firstChild.getAttribute('bill_id');
这行代码在IE6上可以正确执行,但是在FireFox3.5上却没有结果。错误提示:不支持该属性或方法。根据经验判断,应该是tr或者tr.firstChild二者中有一个没有获取正确的对象。于是使用tr.nodeName和tr.firstChild.nodeName进行测试,前者是tr对象没有错误,而后者的值却是#text;而此时使用tr.firstChild.sibling获得就是第一个td对象。
当时就想,FireFox是不是对Table中所有元素都采用了这样的处理,即不是按照table>tbody>tr/th>td的顺序,而是table>#text|tbody>#text|tr>#text|td。于是就写了下面的简单测试程序,进行验证。
<html>
<head>
<title>firstChild Test</title>
<script language="javascript"><!--
function testTable(){
var table = document.getElementById('table1');
var firstChildOfTable = table.firstChild.nodeName;
var tbody = table.getElementsByTagName('tbody')[0];
var firstChildOfTbody = tbody.firstChild.nodeName;
var tr = tbody.getElementsByTagName('tr')[0];
var firstChildOfTr = tr.firstChild.nodeName;
alert('table>' + firstChildOfTable + '|tbody>' + firstChildOfTbody + '|tr>' + firstChildOfTr);
}
// --></script>
</head>
<body>
<table id="table1" border="1">
<tr>
<td>cell1</td>
<td>cell2</td>
</tr>
<tr>
<td>cell3</td>
<td>cell4</td>
</tr>
</table>
<input type="button" value="Test" onClick="testTable()">
</body>
</html>
这是得到结果如下图所示:
从图中可以明显看到TBody的firstChild值就是TR,这和原来的设想并不一样。
仔细观察代码可以发现,TBODY并没有实际写在代码中,而是由浏览器自动加上,那么会不会是这样原因导致的?于是把表格代码改为下面的形式:
<table id="table1" border="1">
<tbody>
<tr>
<td>cell1</td>
<td>cell2</td>
</tr>
<tr>
<td>cell3</td>
<td>cell4</td>
</tr>
</tbody>
</table>
再次运行,结果如图:
证实了上面的假设,即tbody是由FireFox自动加上的。
于是又想,如果表格完全是由JavaScript动态生成,firstChild是不是就不是#text了呢?通过下面的程序测试一下:
function testTable2(){
var table = document.createElement('table');
var tbody = document.createElement('tbody');
table.appendChild(tbody);
var tr = document.createElement('tr');
tbody.appendChild(tr);
var td = document.createElement('td');
tr.appendChild(td);
document.body.appendChild(table);
var firstChildOfTable = table.firstChild.nodeName;
var firstChildOfTbody = tbody.firstChild.nodeName;
var firstChildOfTr = tr.firstChild.nodeName;
alert('table>' + firstChildOfTable + '|tbody>' + firstChildOfTbody + '|tr>' + firstChildOfTr);
}
这次得到的结果:
这就和IE中的结果保持一致。
现在知道了FireFox和IE中对于Table中各元素的firstChild属性有不同的处理,那么就要避开使用firstChild以及其他child相关属性,而使用:getElementById(), getElementsByTagName()此类的方法,使程序具有跨浏览器特性。