简体   繁体   English

使用JScript动态向HTML表添加新行

[英]Adding new row to HTML table dynamically with JScript

I am writing a code in HTML + Jquery and need to add rows to a table dynamically. 我正在用HTML + Jquery编写代码,需要动态向表中添加行。

I've written the code to add the rows dynamically, but it doesn't seem to work. 我已经编写了用于动态添加行的代码,但是它似乎不起作用。

Here is my JScript code : 这是我的JScript代码:

<script language="JavaScript">
        function addRow(tableID) {
            var table = document.getElementById(tableID);

            var rowCount = table.rows.length;
            var row = table.insertRow(rowCount);

            var cell1 = row.insertCell(0);
            var element1 = document.createElement("input");
            element1.type = "date";
            element1.name="datebox[];
            element1.id = "dt";
            cell1.appendChild(element1);

            var cell2 = row.insertCell(1);
            cell2.innerHTML = rowCount + 1;
            var element2 = document.createElement("input");
            element2.type = "select";
            element2.name = "selectbox[]";
            element2.id = "slct";
            cell2.appendChild(element2);

            var cell3 = row.insertCell(2);
            cell3.innerHTML = rowCount + 1;
            var element3 = document.createElement("input");
            element3.type = "text";
            element3.name = "txtbox[]";
            element3.id = "txt";
            cell3.appendChild(element3);
            table.appendChild(cell1);
        }
    </script>

This is my Table: 这是我的桌子:

<table id = "tab" style="width:500px">
    <tr>
        <th>Date</th>
        <th>Treatment Goal</th>
        <th>Comment</th>
    </tr>
    <tr>
        <td><INPUT type="date" name="datebox[]" id = "dt"/></td>
        <td>
            <SELECT name="selectbox[]" id = "slct">
            </SELECT>
        </td>
        <td><INPUT type="text" name="txtbox[]" id = "txt"/></td>
    </tr>
</table>

I am calling the function in the onClick event of a button like this : 我在这样的按钮的onClick事件中调用函数:

<input type="button" id="add" value="+" name="Add" onclick="addRow('tab')"/>

The html page doesn't respond to the click event and nothing happens. html页面不响应click事件,并且没有任何反应。 Cannot understand what's going wrong. 无法理解出了什么问题。

Working Fiddle 工作小提琴

The first problem is a syntax error on this line (you didn't close the double quote): 第一个问题是此行的语法错误(您没有关闭双引号):

element1.name="datebox[];
                        ^ missing "

The second problem is you are appending the cell to the table which is wrong, you should be appending the row: 第二个问题是您将单元格追加到错误的表中,应该追加行:

table.appendChild(row);
                  ^ changed to row from cell

You are missing a quotation mark on the line: 您在行上缺少引号:

element1.name="datebox[];

after the name element. 在名称元素之后。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM