每次使用对象擦除JS数组时,HTML页面都会刷新

时间:2019-05-18 21:37:16

标签: javascript html

好吧,我有一个小项目,我想在其中创建一个带有名称和姓氏的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());```

1 个答案:

答案 0 :(得分:1)

如评论中所述,您应在事件侦听器中删除()。您还必须将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>