我很难在网页上显示表单的结果。我正在使用一个类,一个构造函数,并试图将用户输入分配给对象。问题是我只能显示一个用户输入,每当我尝试执行多个输出时,输出是未定义的。
class person {
constructor(addFirstName, addLastName) {
this.firstname = addFirstName;
this.lastname = addLastName;
};
};
function DisplayInfo() {
first = document.getElementById("addFirstName").value;
let person1 = new person(first);
document.getElementById("display").innerHTML = person1.firstname;
last = document.getElementById("addLastName").value;
let person2 = new person(last);
document.getElementById("display").innerHTML = person2.lastname;
};
showInput.addEventListener("click", DisplayInfo);
<fieldset>
<legend>Enter your first name:</legend>
<input type="text" id="addFirstName">
</fieldset>
<fieldset>
<legend>Enter your last name:</legend>
<input type="text" id="addLastName">
</fieldset>
<fieldset>
<legend>Enter your class:</legend>
<input type="text" id="addClass">
</fieldset>
<fieldset>
<legend>Enter your section:</legend>
<input type="text" id="addSection">
</fieldset>
<fieldset>
<legend>Enter your role:</legend>
<input type="text" id="addRole">
</fieldset>
<fieldset>
<p id="display"></p>
<button id='showInput'>Show: Person/Class/Role</button>
<script src="form.js"></script>
</fieldset>
您不应该为名字和姓氏创建一个单独的人。用两个名字创建一个人。然后在显示区显示它们。
class Person {
constructor(addFirstName, addLastName) {
this.firstname = addFirstName;
this.lastname = addLastName;
};
};
function DisplayInfo() {
let first = document.getElementById("addFirstName").value;
let last = document.getElementById("addLastName").value;
let person = new Person(first, last);
document.getElementById("display").innerHTML = `${person.firstname} ${person.lastname}`;
};
showInput.addEventListener("click", DisplayInfo);
<!DOCTYPE html>
<html>
<head>
<title>FORM</title>
</head>
<fieldset>
<legend>Enter your first name:</legend>
<input type="text" id="addFirstName">
</fieldset>
<fieldset>
<legend>Enter your last name:</legend>
<input type="text" id="addLastName">
</fieldset>
<fieldset>
<legend>Enter your class:</legend>
<input type="text" id="addClass">
</fieldset>
<fieldset>
<legend>Enter your section:</legend>
<input type="text" id="addSection">
</fieldset>
<fieldset>
<legend>Enter your role:</legend>
<input type="text" id="addRole">
</fieldset>
<fieldset>
<p id="display"></p>
<button id='showInput'>Show: Person/Class/Role</button>
<script src="form.js"></script>
</fieldset>
</html>