Javascript事件委托,处理点击元素的父母? [英] Javascript event delegation, handling parents of clicked elements?

查看:117
本文介绍了Javascript事件委托,处理点击元素的父母?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

http://jsfiddle.net/walkerneo/QqkkA/

我在这里看到许多问题,要么在javascript中询问或者回答事件委托,但是我还没有看到如何使用事件委托来执行不会成为点击事件的目标。

I've seen many questions here either asking about or being answered with event delegation in javascript, but I've yet to see, however, how to use event delegation for elements that aren't going to be the targets of the click event.

例如:

HTML:

<ul>
    <li><div class="d"></div></li>
    <li><div class="d"></div></li>
    <li><div class="d"></div></li>
    <li><div class="d"></div></li>
    <li><div class="d"></div></li>
    <li><div class="d"></div></li>
</ul>​

CSS:

ul{
    padding:20px;
}
li{
    margin-left:30px;
    margin-bottom:10px;
    border:1px solid black;

}
.d{
    padding:10px;
    background:gray;
}
​

如果我要添加点击事件处理元素点击时的 li 元素?如果我附加事件处理程序到 ul 元素,那么 div 将永远是目标元素。除了在点击功能中检查目标元素的每个父母,我该如何实现?

What if I want to add a click event to handle the li elements when they're clicked? If I attach an event handler to the ul element, the divs will always be the target elements. Apart from checking every parent of the target element in a click function, how can I accomplish this?

编辑:

我想使用事件委托,而不是:

I want to use event delegation instead of:

var lis = document.getElementsByTagName('li');
for(var i=0;i<lis.length;i++){
    lis[i].onclick = function(){};
}

但是如果我这样做:

document.getElementsByTagName('ul')[0].addEventListener('click',function(e){

    // e.target is going to be the div, not the li
    if(e.target.tagName=='LI'){

    } 
},false);

编辑:我对如何使用Javascript库不感兴趣,我对它们的做法感兴趣,以及如何使用纯js来完成。

I'm not interested in how to use Javascript libraries for this, I'm interested in how they do it and how it can be done with pure js.

推荐答案

这里有一种方法解决它:

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)

这是过度简化的,循环将继续树,甚至超过UL元素。请参阅黑客/事件中的实施一个更完整的例子。

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.

Element.matches Node.contains Node.compareDocumentPosition 方法可以帮助您实现这种类型的功能。

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

这篇关于Javascript事件委托,处理点击元素的父母?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆