添加到.appendChild <table> </table>

时间:2013-04-29 00:37:18

标签: javascript html

每当我尝试在表格中输入新单元格时,它都不会在 bowlersName 值中添加文本。我的Javascript代码有问题吗?它说“未定义”。

<script type="text/javascript">
    /* <![CDATA[ */

    function addBowler() {
        var newBowler = document.getElementsByName('bowlersName').value;
        var tr = document.createElement('tr');
        var td = tr.appendChild(document.createElement('td'));
        td.innerHTML = newBowler;
        document.getElementById("bowlerList").appendChild(tr);
    }
    /* ]]> */
</script>
</head>
<body>
    <!-- HEADER 1 & 2 -->
    <h1>Central Valley Lanes</h1>
    <h2>2008 Bowling Teams</h2>
    Bowler's name <input type="text" name="bowlersName" size="15" /><input type="button" value="Add Bowler" onclick="addBowler()" />

    <h2>Team Roster</h2>   
    <form action="FormProcessor.html" method="get">
        <table border="1" id="bowlerList">
            <tr>
                <td id="empty">Your team roster is empty</td>
            </tr>
        </table>
        <br />
        <input type="button" value="Submit Roster" />
    </form>
</body>

3 个答案:

答案 0 :(得分:6)

尝试更改此行:

td.innerHTML = (" + bowlersName + ");

对此:

td.innerHTML = "(" + bowlersName + ")";

答案 1 :(得分:4)

有两个问题

  1. 没有名为bowlersName的变量,它应该是newBowler
  2. 您的字符串连接错误,(" + bowlersName + ")应为newBowler
  3. 演示:Fiddle

    function addBowler() { 
        var table = document.getElementById("bowlerList");
        var emptyRow = document.getElementById("empty");
        if(emptyRow){
            emptyRow.parentNode.removeChild(emptyRow)
        }
    
        var newBowler = document.getElementsByName('bowlersName')[0].value;
        var tr = document.createElement('tr');
        var td = tr.appendChild(document.createElement('td'));
        td.innerHTML = newBowler;
        table.appendChild(tr);
    }
    

答案 2 :(得分:0)

 <table class="table table-striped" id="dashTable">
            <thead>
                <tr>
                    <th scope="col">#</th>
                    <th scope="col">First</th>
                    <th scope="col">Last</th>
                    <th scope="col">Handle</th>
                </tr>
            </thead>
            <tbody id="task-row">    
            </tbody>
        </table>

现在您可以使用文字字符串插入行了:

            data.forEach((element, i) => {
                console.log(element, i)
                var t = document.getElementById("dashTable");
                var r = document.createElement("TR");
                r.innerHTML = `
                                             <tr>
                                                <th scope="row">${i + 1}</th>
                                                <td>${element.text}</td>
                                                <td>${element.createdAt}</td>
                                                <td>${element.completed}</td>
                                            </tr>
                                    `
                t.tBodies[0].appendChild(r)