使用Javascript将行插入FORM中的HTML表

Inserting Row Into HTML Table within a FORM using Javascript

本文关键字:中的 HTML FORM 插入 Javascript 使用      更新时间:2023-09-26

我正在尝试使用javascript将一行添加到位于表单中的表中。当它在<形成>标记,但一旦代码被<表单>,添加的行将弹出几毫秒,然后消失。

所附代码在Firefox和Mozilla上进行了测试,结果相同。如果我移除<表单>标记,代码运行良好。关于为什么<form>标记是否导致重新加载并使添加的行消失?

<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript">   </script>
<script>
function addTableRow() {
    var len = $('#vendorstbl tr').length
    var table = document.getElementById("vendorstbl");
    var row = table.insertRow(len);
    var cell0 = row.insertCell(0);
    var cell1 = row.insertCell(1);
    cell0.innerHTML = "<select id='test"+len+"'><option name='test"+len+"'>Apple</option><option name='test"+len+"''>Sony</option></select>";
    cell1.innerHTML = "<input type='text' size='25' id='product"+len+"' name='product"+len+"'' value='Enter Data'>";
}
</script>
<html>
<body>
    <h3>Adding Row To Table Test:</h3>
    <form>
        <table class='add' id='vendorstbl'>
        <tr><th>Vendor</th><th>Product</th></tr>
        </table>
        <button onclick='addTableRow()'>Add Row</button>
    </form>
</body>
</html>

您是否考虑过使用AngularJS指令来实现这一点?一个带有一些格式的简单ng Repeat只需几行代码就可以实现这一点。

<table>
    <tr ng-repeat="person in people" ng-class="rowClass(person)">
        <td>{{ person.name }}</td>
    </tr>
</table>

示例:http://jsfiddle.net/xEyJZ/
来源:https://docs.angularjs.org/api/ng/directive/ngRepeat