这里我想在点击提交按钮后将数据输入到文本框中,将文本框数据插入到html表中。在表记录中必须有编辑按钮,单击编辑按钮后,特定记录进入文本框并更新到html表。 在这里我使用了inserCell()(新单元格)之后我无法做到。请重播
function addrow()
{
var name = document.getElementById("txtbox1").value;
var password = document.getElementById("txtbox2").value;
var id = document.getElementById("txtbox3").value;
var age = document.getElementById("txtbox4").value;
var table = document.getElementById("mytable");
var row = table.insertRow(1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var cell5 = row.insertCell(4);
cell1.innerHTML = name;
cell2.innerHTML = password;
cell3.innerHTML = id;
cell4.innerHTML = age;
cell5.innerHTML = "new cell";
}
//html design page
<head>
<script type="text/javascript" src="JavaScript.js"></script>
</head>
<body>
<table class="auto-style1">
<tr>
<td>NAME</td>
<td><input type="text" value="" id="txtbox1" /></td>
<td> </td>
</tr>
<tr>
<td>PASSWORD</td>
<td><input type="text" value="" id="txtbox2" /></td>
<td> </td>
</tr>
<tr>
<td>ID</td>
<td><input type="text" value="" id="txtbox3" /></td>
<td> </td>
</tr>
<tr>
<td>AGE</td>
<td><input type="text" value="" id="txtbox4" /></td>
<td> </td>
</tr>
<tr>
<td></td>
<td><input type="button" VALUE="SUBMIT" id="BTNSUBMIT" onclick="addrow()"/></td>
</tr>
</table>
<table id="mytable" border="1" >
<tr>
<th>NAME</th>
<th>PASSWORD</th>
<th>ID</th>
<th>AGE</th>
</tr>
</table>
</body>
</html>
答案 0 :(得分:1)
从javascript管理html的最简单方法是使用数据绑定库,例如knockout js。
以下是您要实现的目标的实例:
https://jsfiddle.net/up14yz68/
打开该链接,查看已实施功能的所有实时演示。
代码,html:
<table class="auto-style1">
<tbody data-bind="foreach: fields">
<tr>
<td data-bind="text: title"></td>
<td><input type="text" data-bind="value: value"></td>
</tr>
</tbody>
<tr>
<td></td>
<td><input type="button" VALUE="SUBMIT" data-bind="click: addRow"></td>
</tr>
</table>
<table id="mytable" border="1" >
<tr data-bind="foreach: fields">
<th data-bind="text: name"></th>
</tr>
<tbody data-bind="foreach: rows">
<tr data-bind="foreach: $data">
<td data-bind="text: value"></td>
</tr>
</tbody>
</table>
代码,js:
function viewModel() {
var self = this;
self.rows = ko.observableArray([
[
{title: "name", value: "Santiago"},
{title: "password", value: "Pa55w0rd"},
{title: "id", value: "100255"},
{title: "age", value: "28"}
], [
{title: "name", value: "Stack"},
{title: "password", value: "overflow"},
{title: "id", value: "108888"},
{title: "age", value: "13"}
]
]);
self.fields = [
{title: "name", value: ko.observable("John")},
{title: "password", value: ko.observable("secret123")},
{title: "id", value: ko.observable("10001")},
{title: "age", value: ko.observable("50")},
];
self.addRow = function() {
var newRow = [];
self.fields.forEach(function(field) {
newRow.push({title: field.title, value: field.value()});
field.value("");
});
self.rows.push(newRow);
}
}
ko.applyBindings(new viewModel());
随意逛逛小提琴,了解发生了什么。你可以在他们的网站上学习使用淘汰赛,他们有很好的教程。
还有其他替代数据绑定的方法,比如棱角分明,但我觉得淘汰赛非常精简,而且对应用程序的其余部分都不显眼。