开发者

Another appendchild not working in IE

I have a appendChild JS function that works beautifully in all the browsers except IE.

I am using a JS array and appending this data to a table.

http://jsfiddle.net/2waZ2/51/ Has the code - and works fine in fiddle!

I have looked around the other answers and their problems seem to be a bit different to mine. Maybe I just need to make a tbody, but I dont really know how to do that.

Whats the best way to rewrite this to work in Ie?

Append code part as in the fiddle:

var row =  document.createElement('tr');
row.innerHTML = displayArrayAsTable(QR4, 24, 25);
document.getElementById('mytable').appendChild( row ) ; 

function displayArrayAsTable( array, from, to ) {
  var array = array || [],
  from = from || 0,
  to = to || 0;
 var html = '';

 if ( array.length < 1 )
{
  return;
}
if ( to == 0 )
{
    to = array.length - 1;
}
for ( var x = from; x < to + 1; x++ )
 {
html += '<td&开发者_JAVA百科gt;' + array[x] + '</td>';
}
 return html;
}


The best way would be to use insertRow [MDN]:

var row = document.getElementById('mytable').insertRow(-1);
row.innerHTML = displayArrayAsTable(QR4, 24, 25);

As for tBody: Yes, that could be the problem. The browser always generates a tBody element, no matter whether it is specified in the HTML or not.
Maybe you can solve your problem by just appending the new row to this tBody element:

document.getElementById('mytable').tBodies[0].appendChild( row );

But I remember reading that IE had problems with manipulating tables with normal DOM manipulation methods. Whether this applies in this case as well, I don't know. insertRow should work in any case.

Update: Indeed, it seems that IE does not like to append td elements with innerHTML either. A solution would be to pass row also as parameter to displayArrayAsTable and use insertCell [MDN] to create a new cell.

Update 2: For example you can do it like this:

for ( var x = from; x < to + 1; x++ )
{
    var cell = row.insertCell(-1);
    cell.innerHTML = array[x];
}

where row is a fourth parameter of the function and called as:

var row = document.getElementById('mytable').insertRow(-1);
displayArrayAsTable(QR4, 24, 25, row);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜