这里的事情是通过在文本框中输入值来添加表格行。 即,如果我在文本框中输入 2 并单击提交,它将添加两个表行。 我一直在寻找解决方案,但目前似乎找不到答案。
<form align="center" method="GET">
<input type="text" name="users" id="user_id"><br>
<input type="submit" id="mysubmit" value="Submit" onClick="addMoreRows()">
</form>
<table id="tbl_id" style="text-align:center" align="center" valign:"top">
<thead>
<tr>
<th>Name</th>
<th>Score</th>
<th>Points</th>
<th>Total</th>
</tr>
</thead>
</table>
<script type="text/javascript">
var rowsAdd = document.getElementById('tbl_id').insertRow();
var rowsAdded;
function addMoreRows(){
rowsAdded = document.getElementById('user_id').value();
for(int x=0; x<rowsAdded; x++){
var newCell = newRow.insertCell();
newCell.innerHTML="<tr><td><input type='text' name='user_name'></td></tr>";
newCell = newRow.insertCell();
newCell.innerHTML="<tr><td><input type='text' name='score'></td></tr>";
newCell = newRow.insertCell();
newCell.innerHTML="<tr><td><input type='text' name='points'></td></tr>";
newCell = newRow.insertCell();
newCell.innerHTML="<tr><td><input type='text' name='total'></td></tr>";
}
我哪里出错了? 或者所有代码都完全错误?
最佳答案
您当前的代码存在很多问题。首先也是最重要的,点击提交后,您实际上是在提交表单,因此您永远看不到 javascript 的结果 - 您需要用按钮标签替换提交按钮,或者向 onClick 添加“return false”。在循环中,您使用 int 而不是 var 来初始化循环。最后,我认为您的意思是调用“rowsAdd”“newRow”并将其放置在循环中。
<html>
<body>
<form align="center" method="GET">
<input type="text" name="users" id="user_id"><br>
<input type="submit" id="mysubmit" value="Submit" onClick="addMoreRows(); return false;">
</form>
<table id="tbl_id" style="text-align:center" align="center" valign:"top">
<thead>
<tr>
<th>Name</th>
<th>Score</th>
<th>Points</th>
<th>Total</th>
</tr>
</thead>
</table>
<script type="text/javascript">
function addMoreRows() {
var rowsAdded = document.getElementById('user_id').value;
for(var x=0; x<rowsAdded; x++) {
var newRow = document.getElementById('tbl_id').insertRow();
var newCell = newRow.insertCell();
newCell.innerHTML="<tr><td><input type='text' name='user_name'></td></tr>";
newCell = newRow.insertCell();
newCell.innerHTML="<tr><td><input type='text' name='score'></td></tr>";
newCell = newRow.insertCell();
newCell.innerHTML="<tr><td><input type='text' name='points'></td></tr>";
newCell = newRow.insertCell();
newCell.innerHTML="<tr><td><input type='text' name='total'></td></tr>";
}
}
</script>
</body>
</html>
关于javascript - 如何从输入文本框的值动态添加 HTML 表格中的表格行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27088586/