另一个不在IE工作的追加者 [英] Another appendchild not working in IE

查看:116
本文介绍了另一个不在IE工作的追加者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个appendChild JS函数,除了IE之外,在所有浏览器中都能很好地工作。

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

我正在使用JS数组并将这些数据附加到表中。

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

http://jsfiddle.net/2waZ2/51/ 有代码 - 并且在小提琴中工作正常!

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

我已经查看了其他答案,他们的问题似乎与我的有点不同。也许我只需要制作一个tbody,但我真的不知道该怎么做。

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>' + array[x] + '</td>';
}
 return html;
}


推荐答案

最好的办法是使用 insertRow [MDN]

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

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

至于 tBody :是的,那可能是问题。浏览器总是生成 tBody 元素,无论是否在HTML中指定。

也许你可以只需将新行附加到此 tBody 元素即可解决您的问题:

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

但我记得读过IE在使用普通DOM操作方法操作表时遇到问题。在这种情况下是否也适用,我不知道。 insertRow 在任何情况下都应该有效。

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.

更新:确实,IE似乎不想附加 td 元素使用 innerHTML 。解决方案是将 row 作为参数传递给 displayArrayAsTable 并使用 insertCell [MDN] 创建一个新单元格。

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.

更新2:例如,你可以这样做:

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

这篇关于另一个不在IE工作的追加者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆