我正在编写一个表单中的javascript,并将其作为“验证”打印到'id =“printpeople”'。并且它可以工作,但是大约三秒后,表单会自动刷新,p标签也会刷新。除非我点击“提交”按钮,否则页面似乎不会刷新。为什么会这样?
HTML:
<form name="form" id="form" class="form" onsubmit="createperson()" method="post">
<label for="name">Full Name:</label>
<input type="text" name="name" id="name" /><br>
...
<input type="submit" value="Submit" class="submit" />
</form><br>
<p>People:</p>
<p id="printpeople"></p>
使用Javascript:
function person(form){
var name = document.forms["form"]["name"].value;//retrieves name field
...
var person = [name,email,gender,address];//creates new person array
return person;
}
function createperson(form){
var personinstance = person(form);
var personstring = "Name "+personinstance[0]+
"\n"+"Email "+personinstance[1]+
...
stringholder(personinstance, "write");
}
window.peoplecriteria = ["Name: ","Email: ","Gender: ","Address: "];
window.peoplearray = []; //stores all the people in here
window.peoplestring = "";//string that's used for pretty printing.
function stringholder(parameter, readwrite){
window.peoplearray.push(parameter);
window.peoplestring += window.peoplecriteria[0]+window.peoplearray[0];
document.getElementById("printpeople").innerHTML = peoplestring;
}
答案 0 :(得分:2)
使用:
<form name="form" id="form" class="form" onsubmit="createperson();return false" method="post">
您应该阻止表单提交。
这可以使提交函数返回false。默认情况下,onsubmit函数返回true。通过返回false,您声明您不希望提交继续进行。
答案 1 :(得分:0)
您可以停止提交表单,并将以下内容作为createperson(表单)中的第一行:
form.preventDefault();