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);
}
最佳答案
附加新注释时,您是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.
关于javascript - AddEventListener不起作用ES6,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43626342/