简体   繁体   English

javascript电话簿项目添加新记录后刷新页面

[英]javascript phonebook project refreshes page after adding a new record

I have this vanilla js project which is supposed to be a phonebook with add, remove, and search functionalities.我有这个 vanilla js 项目,它应该是一个具有添加、删除和搜索功能的电话簿。

Problem is when I try to add a new record, the record disappears right after showing up.问题是当我尝试添加新记录时,记录出现后立即消失。 I assume the page refreshes but I don't know why.我假设页面刷新,但我不知道为什么。

This is the phonebook function:这是电话簿 function:

function PhoneBook() {
  this.records = [];

  this.add = function (name, phone) {
    const contact = new PhoneBookRecord(name, phone);
    this.records.push(contact);

    // this.records.forEach(function (item) {
      
    // })

    
    console.log(this.records);
    return this;
  };

  this.search = function (name) {
    const result = this.records.includes(name);
  };

  this.remove = function () {

  };
  
}

When a user clicks on the add button on page, the element's onClick event is called and inside that phonebook.add() is called with the name and phone the user has entered.当用户单击页面上的添加按钮时,将调用元素的 onClick 事件,并在其中调用phonebook.add()并使用用户输入的名称和电话。

Link to code on github: https://github.com/newshahn/vanillajsphonebook链接到 github 上的代码: https://github.com/newshahn/vanillajsphonebook

Please let me know if any more information is needed.如果需要更多信息,请告诉我。

I think the issue is the form is submitting when the button is pressed, you need to call e.preventDefault() from the on button click event handlers or it will submit the page.我认为问题是按下按钮时表单正在提交,您需要从 on button click 事件处理程序中调用 e.preventDefault() ,否则它将提交页面。 the onclick = function() {} can take the argument onclick = function(e) {... e.preventDefault() } onclick = function() {}可以接受参数onclick = function(e) {... e.preventDefault() }

With all due respect, id recommend putting the page elements into the html and not building the entire page through dom manipulation in js.恕我直言,id 建议将页面元素放入 html 中,而不是通过 js 中的 dom 操作来构建整个页面。 its was not easy to see what was going on.很难看到发生了什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM