IE v. FF: Is table.tBodies[0] valid?

点点圈 提交于 2020-01-04 06:15:00

问题


From what I gather, tBodies[0] seems to work in IE, but not FF. Is this an IE mistake? I've created a small file to demonstrate the incosistency, and I would like to know the best way to go about this.

The HTML:

<html>
<body>
 <table id="dataGrid">
 </table>
 <input type="button" onclick="insertRow();" value="New row">
</body>
</html>

This script should add a row every time the button is clicked. It works in IE but breaks in Firefox:

<script type="text/javascript" src="/costplan/script/prototype.js"></script>
<script>    
function insertRow(){
 var objTbl = $('dataGrid').tBodies[0]; 
 lastRow = objTbl.rows.length;
 alert(lastRow);
 var newRow = objTbl.insertRow(lastRow);
}
</script>

Is tBodies[0] invalid? I'm not sure why, but this code works in both FF and IE:

<script type="text/javascript" src="/costplan/script/prototype.js"></script>
<script>
function insertRow(){
 var objTbl = $('dataGrid');
 lastRow = objTbl.rows.length;
 alert(lastRow);
 var newRow = objTbl.insertRow(lastRow);
}    
</script>

Are either of these functions correct? Basically, I don't really know what's going on (I gather that at least one of these scripts is invalid, but I don't know which or why).


回答1:


The tBodies property is part of the DOM Level 2 standard, and it works on both browsers.

The difference you are having is that IE always injects a TBODY element as a child of your empty table.

Firefox, Chrome and other browsers don't do it if the element is empty, if the TABLE element has at least one TR or TH, they will create the TBODY implicitly.

You could add the TBODY element by yourself, and your example will work without problems:

<table id="dataGrid">
  <tbody>
  </tbody>
</table>


来源:https://stackoverflow.com/questions/3817832/ie-v-ff-is-table-tbodies0-valid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!