添加到<TR> <TABLE> 带有 .appendChild 的



每次我尝试向表中输入新单元格时,它都不会在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>

尝试更改此行:

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

对此:

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

有两个问题

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

演示: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);
}
 <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)

最新更新