我试图使用Javascript在我的HTML表格中添加包含数据的表格行,但似乎我无法添加。这是为什么?
<html>
<head>
<title>
</title>
<script>
function addUser(){
var tbl = document.getElementById('datatable');
var lastRow = tbl.rows.length;
var iteration = lastRow+1;
var row = tbl.insertRow(lastRow);
var cellLeft = row.insertCell(0);
var textNode = document.createTextNode(iteration);
cellLeft.appendChild(textNode);
}
</script>
</head>
<body>
<table border = 1 id = "datatable">
<tr>
<td>ID</td>
<td>NAME</td>
<td>ADDRESS</td>
</tr>
<tr>
<td>1</td>
<td>Something</td>
<td>Something</td>
</tr>
<tr>
<td>2</td>
<td>Foo</td>
<td>bar</td>
</tr>
</table>
<form id = "myForm" onsubmit = "addUser()">
ID:<input type = "text" name = "txtID"><br />
NAME:<input type = "text" name = "txtName"><br />
ADDRESS:<input type = "text" name = "txtAddress"><br />
<input type = "submit" value = "Add Item">
</form>
</body>
</html>
答案 0 :(得分:2)
您需要的不是提交表格 只是一个onclick事件可以帮助。
<input type = "button" value = "Add Item" onclick="addUser()">
答案 1 :(得分:1)
这是因为你是一个表格。首先调用你的AddUSer并运行,但页面会重新加载,你看到的是初始页面。