MSIE8 compatibility mode not rendering dynamically created table

南笙酒味 提交于 2019-12-21 21:11:44

问题


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' onclick='javascript:AddTable()' />
</body>
</html>

回答1:


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.




回答2:


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);


来源:https://stackoverflow.com/questions/2406706/msie8-compatibility-mode-not-rendering-dynamically-created-table

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