You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

HTML表单提交页面刷新丢数据,JS函数异常触发问题求助

Fixing Your Form Submission & Function Trigger Issues

Hey there! I see you're working on a small form project to collect user data and store it in a JS array—let's get those two bugs sorted out right away.

The First Problem: addPerson() Runs Automatically

Looking at your event listener line:

submit.addEventListener("click", addPerson());

You're actually calling the function immediately (the () after addPerson) instead of passing the function reference to the listener. That's why it runs as soon as the script loads, not when you click the button.

Fix this by removing the parentheses—just pass the function name:

submit.addEventListener("click", addPerson);

The Second Problem: Page Refreshes & Data Loss

Even with the above fix, your form will still refresh when you click the submit button because it's a <button type="submit"> inside a <form> element. By default, this triggers the form's native submit action, which reloads the page. Using preventDefault() is the right idea, but you need to apply it to the event object to block the refresh.

A better practice is to listen to the form's submit event directly (more semantic for form workflows) instead of the button's click event.

Full Corrected Code

Updated HTML (added an ID to the form for easier targeting)

<!DOCTYPE html>
<html>
<body>
<form id="personForm">
  <input id="firstName" type="text" placeholder="First Name">
  <br>
  <input id="lastName" type="text" placeholder="Last Name">
  <br>
  <input id="age" type="number" placeholder="Age">
  <br>
  <button id="submit" type="submit"> Submit! </button>
</form>
<script src="form.js"></script>
</body>
</html>

Updated form.js

// Grab the form element instead of just the button
const personForm = document.getElementById("personForm");

function Person(FirstName, LastName, Age) {
  this.FirstName = FirstName;
  this.LastName = LastName;
  this.Age = Age;
}

const peopleArray = [];

function addPerson(event) {
  // Critical: Stop the form from submitting and refreshing the page
  event.preventDefault();

  const firstName = document.getElementById("firstName").value;
  const lastName = document.getElementById("lastName").value;
  const age = document.getElementById("age").value;

  // Simplified: No need for a nested function to create the object
  const newPerson = new Person(firstName, lastName, age);
  peopleArray.push(newPerson);

  console.log(`New person added: ${firstName} ${lastName}, Age ${age}`);
  console.log(`Total people in array: ${peopleArray.length}`);

  // Optional: Clear the form fields after successful submission
  personForm.reset();
}

// Listen to the form's submit event instead of the button's click
personForm.addEventListener("submit", addPerson);

Extra Little Improvements

  • Added placeholder attributes to inputs for better user clarity
  • Switched from var to const/let for modern JavaScript best practices
  • Removed the unnecessary nested createObject function to simplify the code
  • Added a form reset after submission to make it easier for users to add another person

Now when you submit the form, the page won't refresh, your data will stay safely in the peopleArray, and addPerson() will only run when you click the submit button!

内容的提问来源于stack exchange,提问作者Gerpstarg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 09:03:01