我有一个小项目,我想制作一个 HTML 表单,其中包含保存到对象数组中的姓名和姓氏。听起来简单又酷。好吧,直到你开始制作它......
它只是不保存数据并每次都刷新页面,.preventDefault 没有帮助。
并且出于某种原因,即使未单击提交,addPerson 函数也会触发,完全不知道如何在单击时设置事件监听器 - 为什么它执行未调用但仅定义的函数?
<!DOCTYPE html>
<html>
<body>
<form>
<input id="firstName" type="text"> <br>
<input id="lastName" type="text"> <br>
<input id="age" type="number"> <br>
<button id="submit" type="submit">
Submit!
</button>
</form>
<script src="form.js"></script>
</body>
</html>
var submit = document.getElementById("submit");
function Person (FirstName, LastName, Age) {
this.FirstName = FirstName;
this.LastName = LastName;
this.Age = Age;
}
var peopleArray = [];
function addPerson () {
var firstName = document.getElementById("firstName").value;
var lastName = document.getElementById("lastName").value;
var age = document.getElementById("age").value;
function createObject () {
var newObject = new Person (firstName, lastName, age);
peopleArray.push(newObject);
}
createObject ();
console.log("New person and added to list!" + " " + firstName + " " + lastName + " " + age);
console.log(peopleArray.length);
}
submit.addEventListener("click", addPerson());```
最佳答案
您应该删除事件监听器中的 ()
,如评论中所述。您还必须将 event
参数传递给函数,以便它在内部可用。然后你可以调用preventDefault
。
var submit = document.getElementById("submit");
function Person (FirstName, LastName, Age) {
this.FirstName = FirstName;
this.LastName = LastName;
this.Age = Age;
}
var peopleArray = [];
function addPerson(event) {
event.preventDefault();
var firstName = document.getElementById("firstName").value;
var lastName = document.getElementById("lastName").value;
var age = document.getElementById("age").value;
function createObject () {
var newObject = new Person (firstName, lastName, age);
peopleArray.push(newObject);
}
createObject();
console.log("New person and added to list!" + " " + firstName + " " + lastName + " " + age);
console.log(peopleArray.length);
}
submit.addEventListener("click", addPerson);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input id="firstName" type="text"> <br>
<input id="lastName" type="text"> <br>
<input id="age" type="number"> <br>
<button id="submit" type="submit">Submit!</button>
</form>
关于javascript - 每次用对象删除 JS 数组时刷新 HTML 页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56203033/