insertRow 与appendChild
向表添加行时首选哪种方法?
var tr = tbl.insertRow(-1);
或
var tr = document.createElement('tr'); tbl.appendChild(tr);
?
Which method is preferred for adding a row to a table?
var tr = tbl.insertRow(-1);
or
var tr = document.createElement('tr');
tbl.appendChild(tr);
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
insertRow
会好得多。 A 级浏览器支持它,并且 API 更简洁、更简洁。insertRow
would be the much better. It is supported by grade A browsers and it's less verbose and a cleaner API.我看到了 insertRow 的很好的论点,但我发现了一个缺点:insertRow 只能创建一个新的空行,而appendChild 需要一个现有的行对象。 使用appendChild,您可以在表中移动行,将行从一个表移动到另一个表,或者从表中取出一行然后将其放回(对于分页表非常方便)。 要对 insertRow(和 insertCell)执行相同的操作,您必须打包内容,创建新的行和单元格,然后将旧内容添加到新单元格中。 笨拙,而且效率似乎较低。 有没有更优雅的方法来做到这一点? 采用现有行对象的 insertRow 变体会很好。
I see good arguments for insertRow, but I find one disadvantage: insertRow can only create a new empty row, whereas appendChild takes an existing row object. With appendChild, you can move rows around in a table, move a row from one table to another, or take a row out of a table and later put it back in (very handy for paged tables). To do the same with insertRow (and insertCell), you would have to package up the contents, create new rows and cells, and then add the old contents to the new cells. Clumsy, and seemingly less efficient. Is there a more graceful way to do this? A variant of insertRow that takes an existing row object would be nice.
insertRow
可能被认为更可靠,因为它是 DOM[1]。在所有测试的浏览器(IE6/7、FF3、Chrome2、Opera9)中,当在 DOM 外部操作时,
appendChild
方法始终更快(尽管略有提高),但当尝试修改文档中的表格(更常见的做法)速度明显慢。换句话说:一定要使用
insertRow
。这些测试是在本地进行的,因此可能不可靠,请参阅此处的来源:http://pastie.org/482023
insertRow
might be argued as more reliable since it's DOM[1].The
appendChild
method is consistently faster (albeit marginally) across all tested browsers (IE6/7, FF3, Chrome2, Opera9) when operating outside of the DOM, but when trying to modify tables within the document (a more common endeavour) it's significantly slower.In other words: definitely use
insertRow
.These tests were performed locally so may not be reliable, see the source here: http://pastie.org/482023
如果您确实使用 dom 方法,则应将 tr 附加到 tbody、thead 或 tfoot 元素,而不是附加到 table 元素。
If you do use dom methods, a tr should be appended to a tbody, thead, or tfoot element, and not to a table element.