【问题标题】:IE v. FF: Is table.tBodies[0] valid?IE 诉 FF:table.tBodies[0] 有效吗?
【发布时间】:2012-01-04 22:58:07
【问题描述】:

据我所知,tBodies[0] 似乎可以在 IE 中工作,但不能在 FF 中工作。这是IE错误吗?我创建了一个小文件来演示不一致,我想知道解决此问题的最佳方法。

HTML:

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

每次单击按钮时,此脚本都应添加一行。它在 IE 中有效,但在 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>

tB​​odies[0] 无效吗?我不知道为什么,但这段代码在 FF 和 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>

这些函数是否正确?基本上,我真的不知道发生了什么(我认为这些脚本中至少有一个是无效的,但我不知道是哪个或为什么)。

【问题讨论】:

  • 你用的是原型,对吧?
  • 另外,有效的就是有效的。
  • 正确。据我所知,它只对 $ 函数很重要。
  • 我不知道原型,但为什么在 jquery 中你可以做到$('dataGrid tbody:first')
  • @Pointy 我猜到了,但我想确定并希望理解为什么另一个无效。看来 tBodies[0].rows 应该适合我。

标签: javascript html dom prototypejs


【解决方案1】:

tBodies 属性是 DOM 2 级标准的一部分,它在两个浏览器上都是 works。

您所拥有的不同之处在于 IE 总是将 TBODY 元素作为空表的子元素注入。

Firefox、Chrome等浏览器如果元素为空则不会这样做,如果TABLE元素至少有一个TR或TH,它们会隐式创建TBODY。

您可以自己添加TBODY 元素,您的example 将毫无问题地工作:

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

【讨论】:

    猜你喜欢
    • 2011-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-07
    • 1970-01-01
    • 2021-10-22
    • 2021-05-31
    • 2018-07-19
    相关资源
    最近更新 更多