Javascript event delegation, handling parents of clicked elements?

允我心安 提交于 2019-11-28 20:40:36

Here's one way to solve it:

var list = document.getElementsByTagName('ul')[0]

list.addEventListener('click', function(e){
  var el = e.target
  // walk up the tree until we find a LI item
  while (el && el.tagName !== 'LI') {
     el = el.parentNode
  }
  console.log('item clicked', el)
}, false)

This is overly simplified, the loop will continue up the tree even past the UL element. See the implementation in rye/events for a more complete example.

The Element.matches, Node.contains and Node.compareDocumentPosition methods can help you implement this type of features.

There is now a method on elements called closest, which does exactly this. It takes a CSS selector as parameter and finds the closest matching ancestor, which can be the element itself. All current versions of desktop browsers support it, but in general it is not ready for production use. The MDN page linked above contains a polyfill.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!