开发者

MSIE8 compatibility mode not rendering dynamically created table

A bit weird... ...if running in IE8 quirks mode or in compatibility view mode, the table added by the following code doesn't render. Can anyone tell me why, because it is not obvious to me..?

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script>
function AddTable()
{
  var table = document.createElement('table');
  var row = document.createElement('tr');
  table.appendChild(row);
  var cell = document.createElement('td');
  cell.innerHTML='abc';
  row.appendChild(cell);
  var divContainer = document.getElementById('divContainer');
  divContainer.appendChild(table);
}
</script>
</head>
<body>
<div id='divContainer'>
</div>
<input type='button' value='add table' oncli开发者_StackOverflow社区ck='javascript:AddTable()' />
</body>
</html>


Microsoft has a page that may illuminate what's going on.

http://msdn.microsoft.com/en-us/library/ms532998(VS.85).aspx#TOM_Create

For dynamically building tables they advocate the "Table Object Model", which uses methods like insertRow() and insertCell() to do the job you're doing with the DOM methodscreateElement() and appendChild(). It's also OK if you use the DOM methods, but "Internet Explorer requires that you create a tBody element and insert it into the table when using the DOM. Since you are manipulating the document tree directly, Internet Explorer does not create the tBody, which is automatically implied when using HTML."

The table object model works in the couple of browsers I tested it in (Chrome and Firefox on the Mac), so it may not be a bad idea to familiarize yourself with it. Or if you want to stick with the DOM methods, add the tBody element, because IE requires it.

If you add the following code to the end of your AddTable() method you'll see how the two compare (mainly, the second table will have a tBody in it). And it will render in IE8.

 // now the Table Object Model way
  table = document.createElement('table');
  row = table.insertRow(-1) ;
  cell = row.insertCell(-1) ;
  cell.innerHTML='def';
  divContainer.appendChild(table);

Hope this helps.


Try adding a tbody element

Instead of

  var row = document.createElement('tr');
  table.appendChild(row);

do

  var tbody = document.createElement('tbody');
  var row = document.createElement('tr');
  tbody.appendChild(row);
  table.appendChild(tbody);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜