addEventListener firing twice

I'm creating a simple phonebook, that adds person name, last name and phone into a div and into the DOM, with option to delete this div with click event. I have a class called Phonebook which contain these 2 functions:

//add an event button to all divs inside the DOM
this.deleteBtnEvent = function(){
    var _this = this;
    //get all the divs that currently on the DOM
    var deleteBtn = document.getElementsByClassName('delete');
    for (var i = 0; i < deleteBtn.length; i++) {
        deleteBtn[i].addEventListener('click', function(e){
            _this.removeContact(e.target.parentElement.attributes.index.value);
        });
    }   
};

//remove the div from the array and from the DOM
this.removeContact = function(index){
    var contactsHolder = document.getElementById('contacts');
    var contact = document.getElementsByClassName('contact');
    this._contacts.splice(index, 1);

    contactsHolder.removeChild(contact[index]);

    //update localstorage
    var stringArr = JSON.stringify(this._contacts);
    localStorage.setItem('data', stringArr);

    console.log('current: ');
    console.log(this._contacts);
};

for some reason the addEventListener is firing twice. first time that the addEventListener is called, the function delete the div from the DOM and the array, the second time the listener is fired, i'm getting an error because the div with the same ID doesn't exist, because its already deleted. I'm wondering if there's a way to solve this issue.


In addContact() , you call this.deleteBtnEvent() , presumably to bind deletion to the delete button that was just added. In deleteBtnEvent() , however, you're binding an event listener to all delete buttons on the page. This means the following will happen:

  • Add a contact. A new contact will show up with a delete button that has a listener.
  • Add a second contact. A new contact will show up with a delete button that has a listener, and a second listener will be added to the first button.
  • Add a third contact. A new contact will show up with a delete button that has a listener, and a third listener will be added to the first button, and a second listener will be added to the second button.
  • etc....
  • So, in deleteBtnEvent() , don't add (duplicate) listeners to all delete buttons. Instead, only add a listener to the delete button that was just created via addContact() .

    链接地址: http://www.djcxy.com/p/51952.html

    上一篇: 返回另一个(相同)XMLHttpRequest的链接

    下一篇: addEventListener触发两次