函数在我的div中创建一个表

时间:2014-03-26 20:12:36

标签: javascript html css

我创建了一个函数create_table(...),它应该将表的HTML添加到给定元素的内部HTML的末尾。下面的代码应该发生的是当我单击Show Tree按钮时,应该在第三个div中创建一个表。出于某种原因,我收到错误Property 'getElementById' of object #<HTMLDocument> is not a function。任何帮助非常感谢。

<html>
<head>
<style type="text/css">
    div
    {
        border: 1px dashed;
    }
    table
    {
        border: 1px dashed red;
    }
    #instructdiv
    {
    }

    #inputdiv
    {

    }

    #outputdiv
    {

    }


</style>
<script type="text/javascript">

    function create_table(rows, columns, elementId)
    {
        /* Adds at the end of the HTML for a container with 
           elementId the HTML for a table with a specified 
           number of rows and columns. 
        */
        var newHTML = document.getElementById(elementId).innerHTML;
        newHTML += "<table>";
        for (var i = 0; i < rows; ++i)
        {
            newHTML += "<tr>";
            for (var j = 0; j < columns; ++j)
                newHTML += "<td>j</td>";
            newHTML += "</tr>";
        }
        newHTML += "</table>";
        document.getElementById = newHTML;
    }
    function make_tree()
    {
        /*  To do: Determine number of rows and columns by user input. 
            For testing now, just make the table an arbitrary size.
        */
        create_table(4,50, "outputdiv");
    }
</script>
</head>
<body>
    <div id="instructdiv">
        <p>In the text field below, enter integers in the range 0 through 127 separated by spaces,
           then push Show Tree.</p> 
    </div>
    <div id="inputdiv">
        <textarea id="inputText" scrolling="yes"></textarea>
        <p></p>
        <button onclick="make_tree()">Show Tree</button>
    </div>
    <div id="outputdiv">
         <!-- binary tree table is housed here -->
    </div>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

将您的代码更改为此。你不应该将document.getElementById(这是一个函数)分配给一个字符串,因为该函数是不可用的。

function create_table(rows, columns, elementId)
{
    /* Adds at the end of the HTML for a container with 
       elementId the HTML for a table with a specified 
       number of rows and columns. 
    */
    var element = document.getElementById(elementId);
    var newHTML = element.innerHTML;
    newHTML += "<table>";
    for (var i = 0; i < rows; ++i)
    {
        newHTML += "<tr>";
        for (var j = 0; j < columns; ++j)
            newHTML += "<td>j</td>";
        newHTML += "</tr>";
    }
    newHTML += "</table>";
    element.innerHTML = newHTML;
}
function make_tree()
{
    /*  To do: Determine number of rows and columns by user input. 
        For testing now, just make the table an arbitrary size.
    */
    create_table(4,50, "outputdiv");
}