javascript 将事件侦听器添加到Element

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 将事件侦听器添加到Element相关的知识,希望对你有一定的参考价值。

// To add an event listener in js, first grab the element and store in a var:
var todoUl = document.querySelector('ul');
// Then add the event listener to it:
todoUl.addEventListener('click', function(event){
  // get the exact element that was clicked and make sure it was a <button> with classname of 'deleteButton'
  var elementClicked = event.target;
  if (elementClicked.className === 'deleteButton'){
    handlers.deleteTodo(parseInt(elementClicked.parentNode.id));
  }
}
//EVENT DELEGATION - this is called event delegation because we set up the event handler on the <ul> (which is the single common parent) on therefore only needed one event handler and then we wait for clicks on the delete buttons inside every <li>. This is better than having an event handler for every <li>.

//When using 'event' as an argument in the event listener you can use event.target.tagName to get the element you are looking for.

以上是关于javascript 将事件侦听器添加到Element的主要内容,如果未能解决你的问题,请参考以下文章

如何将事件侦听器添加到动态创建的复选框并检查是不是选中了复选框。 JavaScript

添加事件监听器的最佳实践(javascript、html)

每当将 QWidget 添加到 QApplication 的小部件树时,如何接收事件?

如何使用事件侦听器将类切换到单个列表项

将EventListener 添加到innerHTML

如何在 javascript 中为所有事件添加事件侦听器而不单独列出它们?