Javascript 如何使用 createElement 创建新表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2324782/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:47:22  来源:igfitidea点击:

How to use createElement to create a new table?

javascriptdom

提问by yeeen

Why the following code doesn't work?

为什么下面的代码不起作用?

<html>
<head>
    <script type="text/javascript">
    function addTable() {
        var table = document.createElement('table');
        table.innerHTML = "<tr><td>123</td><td>456</td></tr>";
        document.getElementById("addtable").appendChild(table);
    }
    </script>
</head>
<body>
    <input type="submit" value="New Table" onClick="addTable()"/>
    <div id="addtable"></div>
</body>
</html>

回答by Roland Bouman

To the best of my knowledge, setting the innerHTML property of a tableelement or table section element (like tbodyor thead) does not work on Internet Explorer (EDIT: I just checked - with ietesterand plain IE8. Result is "unknown runtime error" for IE6 and IE8, and it crashes IE7 but that might be an IEtester specific problem).

据我所知,设置table元素或表格部分元素(如tbodythead)的 innerHTML 属性在 Internet Explorer 上不起作用(编辑:我刚刚检查过 - 使用ietester和普通 IE8。结果是 IE6 的“未知运行时错误”和 IE8,它使 IE7 崩溃,但这可能是 IEtester 特定的问题)。

The DOM standardway of adding rows to a table is using the insertRow()method on a table or table section element (look for HTMLTableElement and HTMLTableSectionElement in that DOM spec) :

向表格添加行的DOM 标准方法是使用insertRow()表格或表格部分元素上的方法(在该 DOM 规范中查找 HTMLTableElement 和 HTMLTableSectionElement):

<script type="text/javascript">
function addTable() {
    var c, r, t;
    t = document.createElement('table');
    r = t.insertRow(0); 
    c = r.insertCell(0);
    c.innerHTML = 123;
    c = r.insertCell(1);
    c.innerHTML = 456;
    document.getElementById("addtable").appendChild(t);
}
</script>

In the script, there is no explicit table section being created. AFAIK, a TBODY is automatically created, and rows are inserted in there.

在脚本中,没有创建显式表部分。AFAIK,会自动创建一个 TBODY,并在其中插入行。

EDIT: regarding IE, I should point out that you can add a table with content and all by setting the innerHTMLproperty, but the html you inject in there must be a complete table. So this does work, even on IE:

编辑:关于 IE,我应该指出您可以通过设置innerHTML属性来添加包含内容和所有内容的表格,但是您注入的 html 必须是一个完整的表格。所以这确实有效,即使在 IE 上:

<script type="text/javascript">
function addTable() {
    var html = "<table><tr><td>123</td><td>456</td></tr></table>";
    document.getElementById("addtable").innerHTML = html;
}
</script>

回答by Metin SEV?ND?K

//_table my current table
var table = document.createElement('table'); //new table
table.innerHTML = _table.innerHTML; //clone table innerHTML