我有一个表格,表格顶部出现一个额外的空白单元格。您输入一个名称,该名称就会插入表中,顶部有一个计数器可以计算有多少个名称。有人可以看看我的代码并告诉我如何修复它。
var userNames = [];
function getName() {
//Variables
var input;
var userName;
//Initializes input
input = document.getElementById("nameInput");
//Reads input
userName = input.value;
//Assigns userName
userNames[userNames.length] = userName;
//Clears the input
input.value = "";
input.focus();
}
function printTotal() {
//Constants
var LABEL = "Total: ";
//Variables
var total;
var output;
//Initializes output
output = document.getElementById("totalOutput");
//Gets number
total = userNames.length;
//Output
output.innerHTML = LABEL + total;
}
function printNames() {
//Constants
var OPEN_CELL = "<tr style=\"height : 1.5eM;\"><td>";
var CLOSE_CELL = "</tr></td>";
var ONE = 1;
//Varialbles
var output;
var index;
output = document.getElementById("nameOutput");
index = userNames.length - ONE;
output.innerHTML += OPEN_CELL + userNames[index] + CLOSE_CELL;
}
function project62Part2() {
// Your code goes in here.
getName();
printTotal();
printNames();
return false;
}
HTML 文件代码
<div id="outputDiv" class="output">
<form action="#" onsubmit="return project62Part2();">
<label for="nameInput" style="float : left;">Name:</label>
<input type="text" id="nameInput" style="float : left;" />
<input type="submit" value="submit" style="float : left; clear : left" />
<!--<p id="totalOutput">
</p>-->
<table id="nameOutput">
<tr>
<th id="totalOutput">
Total: 0
</th>
</tr>
</table>
</div>
<script type="text/javascript">project62Part2();</script>
最佳答案
您在页面加载时运行 Project62Part2()。您对 userNames[userNames.length] 的使用实际上是正确的,因为您在基于 0 的数组的尾部添加了一个新项目。但是,当输入为空时,您最初执行 getName 时会将空字符串插入到 userNames[0] 中。
我建议一些基本的验证:
if (userName != "")
userNames[userNames.length] = userName;
您可能不想插入空格,是吗?
关于javascript - 我的 table 有一个额外的单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20645591/