如何使用createElement创建新表? [英] How to use createElement to create a new table?

查看:74
本文介绍了如何使用createElement创建新表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么以下代码不起作用?

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>


推荐答案

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

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

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

The DOM standard way 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) :

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

在脚本中,没有创建显式表部分。 AFAIK,自动创建TBODY,并在那里插入行。

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

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

regarding IE, I should point out that you can add a table with content and all by setting the innerHTML property, but the html you inject in there must be a complete table. So this does work, even on 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>

这篇关于如何使用createElement创建新表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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