我希望用户通过提示符输入“零件ID”和“数量”,并将这些值添加到表中;到目前为止,我已经做到了。之后,我想使用相同的方法在第一行下面添加另一行,从而导致两行具有不同的值,等等。
<html>
<head>
</head>
<!--CREATE AND POPULATE TABLE -->
<body onload="partID(); qty()">
<table id="resultsTable" border=".5px" class="results">
<tr><th>Part ID</th><th>Quantity</th>
<tr>
<td id="partID">Part ID</td>
<td id="qty">Quantity</td>
</tr>
</table>
<br>
<!-- I want this f('createTable') to bring the prompt back and append to existing table onclick, if that makes sense -->
<button onclick="createTable()">Add Another Part</button>
</body>
<!-- LOCAL SCRIPTS -->
<script>
function partID(){
var partID = prompt("Enter part ID:");
var x = document.getElementById('partID');
x.innerHTML = partID;
}
function qty(){
var qty = prompt("Enter Quantity:");
var y = document.getElementById('qty');
y.innerHTML = qty;
}
</script>
</html>
我可以使它工作一次,但是我不确定如何在新行中重复它,又不会丢失以前的数据。
答案 0 :(得分:0)
您想要做的是将数据追加到表中,现在您正在设置单个单元格的值,而不仅仅是将它们追加到已经存在的值上。
JavaScript有一个简洁的附加快捷方式(就像许多其他语言一样),+=
,基本上var myVar = 'Foo'; myVar += 'Bar';
等于var myVar = 'Foo'; myVar = myVar + 'Bar';
function add() {
//prompt the user with boxes for the ID and quantity
var partID = prompt("Enter part ID:");
var qty = prompt("Enter Quantity:");
//generate the HTML for a new table row and insert the given values
var table_html = "<tr><td>" + partID + "</td><td>" + qty + "</td></tr>";
//append the HTML to the already existing HTML in the table
document.getElementById('resultsTable').innerHTML += table_html;
}
/*I dont like default buttons*/
button {
background-color: lightgrey;
color: black;
padding: 8px;
border: 0px;
}
button:hover {
background-color: grey;
}
<html>
<head>
</head>
<body onload="add();">
<!-- instead of onload use a button so the user can repeat the action multiple times -->
<button onclick="add();">Add part</button>
<hr>
<table id="resultsTable" border=".5px" class="results">
<tr>
<th>Part ID</th>
<th>Quantity</th>
</tr>
</table>
<br>
</body>
</html>
如果您需要有关代码的进一步说明,请留下评论。
祝你好运。
答案 1 :(得分:0)
据我了解,您希望能够向<table>
添加新行。为此,您可能要使用一个按钮。
<button onclick="addRow()">Add row</button>
然后您可以使用insertAdjacentHTML
添加一行:
function addRow() {
var table = document.getElementById('resultsTable');
var partID = prompt("Enter part ID:");
var qty = prompt("Enter Quantity:");
table.insertAdjacentHTML('beforeend', "<tr><td>" + partID + "</td><td>" + qty + "</td></tr>")
}
使用insertAdjacentHTML
比替换整个表innerHTML
更安全,更有效。