Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
336 views
in Technique[技术] by (71.8m points)

javascript - How to use createElement to create a new table?

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 (EDIT: 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).

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>

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...