AddEventListener不工作ES6

时间:2017-04-26 06:13:22

标签: javascript ecmascript-6

AddEventListener只附加到最后一个元素,有人可以告诉我它为什么会发生吗?

listNote(key, value){
    let note = `<div class="mdl-cell--4-col-desktop mdl-card__supporting-text mdl-cell--12-col mdl-shadow--2dp mdl-cell--4-col-tablet mdl-card mdl-cell sticky-note">
        <div class="message">${value}</div>
        <div class="date">Created on ${this.date}</div>
        <button id=note-${key} class="delete mdl-button mdl-js-button mdl-js-ripple-effect" data-upgraded=",MaterialButton,MaterialRipple">Delete
            <span class="mdl-button__ripple-container">
                <span class="mdl-ripple">
                </span>
            </span>
        </button>
        </div>`
        this.allnotes.innerHTML += note;
        document.querySelector(`#note-${key}`).addEventListener("click", this.deleteNote);
}

1 个答案:

答案 0 :(得分:1)

当你追加新笔记时,你是removing all the children of allnotes (those which have event listeners), and then creating them again (without event listeners),然后只在最后一个元素上附加一个事件监听器。

相反,如果您想保留解决方案的其余部分,我建议您使用insertAdjacentHTML(...)。这样您就不会重新创建this.allnotes内的节点,而只是添加新节点。所有旧的事件听众都留在旧笔记上!

this.allnotes.insertAdjacentHTML('beforeend', note)

I've made a simple pen to show how this works.