javascript - 使用 javascript(无库)更新 tbody 的 html : possible?

标签 javascript html internet-explorer innerhtml

我想更新 TBODY 的内容(不是整个 TABLE,因为其中有更多的半元数据 (LOL))。我从服务器 (XHR) 得到 >= 0 TR,我想在现有表中填充这些。新的 TR 必须覆盖现有的 TBODY 内容。

我做了一个非常简单的静态 example on jsFiddle可以在 Chrome 中运行,可能在所有其他浏览器中运行,除了 IE(我只使用 Chrome 并在 IE8 中测试)。

在 Chrome 中,第一次尝试成功了:使 TBODY 中的 TR 饱满。没问题!
在 IE 中它不会......我已经包含了一个不起作用的例子来说明我想要让它工作的东西。

我确定这个问题不是新问题:我如何在现有 TBODY 中插入带有 TR 的字符串?

附言。 jQuery 对此没有问题!?它在这里用于SO。 jQuery 对 HTML 做了一些事情然后将它作为 HTML 节点插入..?或者其他的东西?我看不懂那个疯狂的图书馆。碰巧 in this file (寻找 "html: function("。这就是魔法开始的地方。

有没有人有让这个没有 JS 库工作的功能或想法?

最佳答案

Here是关于 innerHTML 和 IE 问题的好资源。

底线是 tbody 上的 innerHTML 属性是只读的。

这是其中一条评论中提出的解决方案:

var innerHTML = "<tr><td>Hello world!</td></tr>";
var div = document.createElement("DIV");
div.innerHTML = "<table>" + innerHTML + "</table>";
// Get the tr from the table in the div
var trElem = div.getElementsByTagName("TR")[0];

关于问题的 jQuery 部分:

//inside the html() function:
// If using innerHTML throws an exception, use the fallback method
} catch(e) {
  this.empty().append( value );
}

//inside the empty() function (basically removes all child nodes of the td):
while ( elem.firstChild ) {
  elem.removeChild( elem.firstChild );
}

//append calls domManip applying this to all table rows:
if ( this.nodeType === 1 ) {
  this.appendChild( elem );
}

//domManip as far as I can tell creates a fragment if possible and calls the three lines above with this=each row in turn, elem=the tbody(created if missing)

关于javascript - 使用 javascript(无库)更新 tbody 的 html : possible?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5888554/

相关文章:

javascript - 如果未单击按钮如何运行函数?

javascript - 无法将新数据添加到基于 switch case 的数组

带边距的 CSS 错误(仅在 IE 中?)

internet-explorer - 有人可以解释 Internet Explorer 中 "Version"和 "Update Versions"之间的区别吗?

javascript - 如何在html Canvas 上replaceByImage()而不是drawImage()(忽略不透明度)?

javascript - Flowbite 不适用于组件,但适用于根

html - 当向右浮动链接时,IE11 中出现滚动条

javascript - 使用 JQuery $.children() 和 $.each() 遍历 data-* 元素?

html - 三个框不对齐顶部

javascript - Meteor 设置整体模板上下文