【发布时间】:2019-10-22 12:23:11
【问题描述】:
我的 HTML 页面有问题。我的程序旨在使用表格收集姓名,然后将它们输出到表格下方的表格中。当页面没有重新加载时,它能够做到这一点。
当我第一次输入某个名称时,页面会重新加载。页面重新加载后,我输入了相同的名称,以后按回车键就不会重新加载。我不知道这是为什么,也不知道如何解决。
这里是链接的JS文件
// Gloabal Variables
var enteredName,
countOutput,
count,
table,
form,
allNames = [];
function project62Part2() {
// Your code goes in here.
function getElements() {
form = document.getElementById("nameForm");
countOutput = document.getElementById("numNames");
table = document.getElementById("table");
}
function addName() {
enteredName = form.name.value;
allNames.push(enteredName);
}
function countNames() {
// Reset count
count = 0;
// Loop through and count names
for (i = 0; i < allNames.length; i++) {
count++;
}
}
function output() {
// Reset table
table.innerHTML = "<tr><th>Names</th></tr>";
// Display count
countOutput.innerHTML = "Total names entered: " + count;
// Loop through and add to table display
for (i = 0; i < allNames.length; i++) {
table.innerHTML += "<tr><td>" + allNames[i] + "</td></tr>";
}
}
// Call code
getElements();
addName();
countNames();
output();
// Prevent page from reloading
return false;
}
<form id="nameForm" action="#">
<label class="formLabel" for="name">Name: </label>
<input id="name" name="name" />
<input type="submit" name="runExample" value="Submit" class="formatSubmit" onclick="project62Part2()" />
</form>
<div id="numNames">Total names entered: </div>
<table id="table"></table>
我对编码的理解充其量只是初步的,所以虽然我很感激任何答案,但我希望它保持简单!
【问题讨论】:
-
只使用 JavaScript 自己:
formElement.onsubmit = project62Part2;
标签: javascript html forms reload