为什么在“ LocalStorage”中添加/删除元素无效?

时间:2018-07-15 11:18:29

标签: javascript oop dom ecmascript-6 local-storage

我想使用以下方法在localStorage中添加:addContact()中用户的姓名,电话和邮件,并使用localStorage中的数据来创建表使用方法show()

也不会删除联系人,我正在尝试使用方法deleteContact(e)

  • 添加联系人时,出现以下错误:Uncaught TypeError: Cannot read property 'value' of undefined
  • 删除时收到以下错误:Uncaught TypeError: Cannot read property 'splice' of undefined

帮我解决这个问题

//Product Creation Class
class LocalStorage {
    constructor(name, phone, email) {
        this.name = name;
        this.phone = phone;
        this.email = email;

    }
}
// Сlass where products are recorded
class Book {
    constructor() {

        this.products = [];
        this.name = document.getElementById("name");
        this.phone = document.getElementById("phone");
        this.email = document.getElementById("email");
        this.buttAdd = document.getElementById("add");
        this.book = document.getElementById("addBook");
    }

    //method for adding a product
    addContact() {
        let isNull = this.name.value != '' && this.phone.value != '' && this.email.value != '';
        if (isNull) {
            let obj = new LocalStorage(this.name.value, this.phone.value, this.email.value);
            this.products.push(obj);
            localStorage['addbook'] = JSON.stringify(this.products);
            this.show();
        }
    }

    //method for remove product by name
    deleteContact(e) {
        if (e.target.className === "delbutton") {
            let remID = e.target.getAttribute('data-id');
            this.products.splice(remID, 1);
            localStorage['addbook'] = JSON.stringify(this.products);
            this.show();
        }
    }

    // method to draw the table with product property (
    // name, phone, email)
    show() {
        if (localStorage['addbook'] === undefined) {
            localStorage['addbook'] = '';
        } else {
            this.products = JSON.parse(localStorage['addbook']);

            this.book.innerHTML = '';
            for (let e in this.products) {
                let table = `          <table id="shop" class="entry">
                <tr>
                    <th>Name:</th>
                    <th id="filter">Phone:</th>
                    <th>Email:</th>
                    <th class="dels"></th>
                </tr>
                <tbody>
                <tr class="data">
                <td>${this.products[e].name}</td>
                <td>${this.products[e].phone}</td>
                <td>${this.products[e].email}</td>
                <td class="del"><a href="#" class="delbutton" data-id="' + e + '">Delete</a></td>
</tr>
</tbody>
            </table>`;
                this.book.innerHTML += table;
            }
        }

    }

    OperationsWithContacts() {
        // add new product by click
        this.buttAdd.addEventListener('click', this.addContact);
        // delete product by name after click
        this.book.addEventListener('click', this.deleteContact);
        console.log(this.products);
    }
}

let shop = new Book();
shop.show();
shop.OperationsWithContacts();
<div class="Shop">
    <div class="add-product">
        <h1>Add product</h1>
        <form name="addForm">
            <label for="name" >Name of product</label>
            <input type="text"  id="name" class="input-product">
            <label for="phone">Price of product</label>
            <input type="number" id="phone" class="input-product">
            <label for="email">Count of product</label>
            <input type="text" id="email" class="input-product">
            <button id="add" type="button">Add</button>
        </form>
    </div>
    <div class="product-table">
        <h2>Address book</h2>
        <div id="delete-form">
            <label for="name-delete">Search product by name</label>
            <input type="text" id="name-delete" class="input-delete">
        </div>
        <div id="addBook"></div>
    </div>
</div>

enter code here

1 个答案:

答案 0 :(得分:1)

我看到的一个明显问题是,函数thisaddContact()中的deleteContact()代表一个button-HTML元素,而不是您认为的类。

只需更改一下代码,您就会看到: //添加产品的方法

addContact() {
    console.log('addContact()', this);

    let isNull = this.name.value != '' && this.phone.value != '' && this.email.value != '';
    if (isNull) {
        let obj = new LocalStorage(this.name.value, this.phone.value, this.email.value);
        this.products.push(obj);
        localStorage['addbook'] = JSON.stringify(this.products);
        this.show();
    }
}

因此,您可能希望将绑定从以下位置更改:

document.querySelector('#add').addEventListener('click', this.addContact);

document.querySelector('#add').addEventListener('click', this.addContact.bind(this));

正确使用this快捷方式。

编辑:

//Product Creation Class
//REM: Not the best name choice here.. localStorage <> LocalStorage
class LocalStorage{
  constructor(name, phone, email){
    this.name = name;
    this.phone = phone;
    this.email = email
  }
};

//Сlass where products are recorded
class Book{
  constructor(){
    this.products = [];
    this.name = document.getElementById("name");
    this.phone = document.getElementById("phone");
    this.email = document.getElementById("email");
    this.buttAdd = document.getElementById("add");
    this.book = document.getElementById("addBook")
  };

  //method for adding a product
  addContact(){
    let isNull = this.name.value != '' && this.phone.value != '' && this.email.value != '';
    if(isNull){
      let obj = new LocalStorage(this.name.value, this.phone.value, this.email.value);
      this.products.push(obj);
      localStorage['addbook'] = JSON.stringify(this.products);
      this.show();
    }
  };

  //method for remove product by name
  deleteContact(e) {
    if(e.target.className === "delbutton"){
      let remID = e.target.getAttribute('data-id');
      this.products.splice(remID, 1);
      localStorage['addbook'] = JSON.stringify(this.products);
      this.show();
    }
  };

  //method to draw the table with product property (
  //name, phone, email)
  show(){
    if(localStorage['addbook'] === undefined) {
      //REM: An empty string is no valid JSON to be serialised
      localStorage['addbook'] = '[]'
    }
    else{
      this.products = JSON.parse(localStorage['addbook']);
      this.book.innerHTML = '';

      for(let e in this.products){
        let table = `          <table id="shop" class="entry">
          <tr>
          <th>Name:</th>
          <th id="filter">Phone:</th>
          <th>Email:</th>
          <th class="dels"></th>
          </tr>
          <tbody>
          <tr class="data">
          <td>${this.products[e].name}</td>
          <td>${this.products[e].phone}</td>
          <td>${this.products[e].email}</td>
          <td class="del"><a href="#" class="delbutton" data-id="' + e + '">Delete</a></td>
          </tr>
          </tbody>
          </table>`;

        this.book.innerHTML += table;
      }
    }
  };

  OperationsWithContacts(){
    // add new product by click
    this.buttAdd.addEventListener('click', this.addContact.bind(this));

    // delete product by name after click
    this.book.addEventListener('click', this.deleteContact.bind(this));
    console.log(this.products);
  }
};

;window.onload = function(){
  let shop = new Book();
  shop.show();
  shop.OperationsWithContacts()
};
<div class="Shop">
  <div class="add-product">
    <h1>Add product</h1>
    <form name="addForm">
      <label for="name" >Name of product</label>
      <input type="text"  id="name" class="input-product">
      <label for="phone">Price of product</label>
      <input type="number" id="phone" class="input-product">
      <label for="email">Count of product</label>
      <input type="text" id="email" class="input-product">
      <button id="add" type="button">Add</button>
    </form>
  </div>
  <div class="product-table">
    <h2>Address book</h2>
    <div id="delete-form">
      <label for="name-delete">Search product by name</label>
      <input type="text" id="name-delete" class="input-delete">
    </div>
    <div id="addBook"></div>
  </div>
</div>