点击时的Javascript事件监听器无法按预期工作 [英] Javascript Event Listener on click not working as expected

查看:103
本文介绍了点击时的Javascript事件监听器无法按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个事件侦听器,通过将其放在主体上并执行一些事件委派来处理所有点击。我试图做的一个简单的例子是:

 < html> 
< body>
< div id =div1>
< ul>
< li> 1< / li>
< li> 2< / li>
< li> 3< / li>
< ul>
< / div>
< script>
document.body.addEventListener('click',function(e){
if(e.target.id ==div1){alert(hi)}
})
< / script>
< / body>
< / html>

我对上述代码的期望是,当我点击li元素时,alert会因为它嵌套在父div中而触发。我认为这个事件会传播给家长并开火。但是,如果我点击li元素,它似乎并不工作。有人可以帮助解释发生了什么?谢谢!



如果我这样做的话,通过将eventListener直接添加到div id,它就可以工作。

解决方案

有两个元素与一个事件相关:


  1. event.currentTarget ,其中是实际调用侦听器的元素(即侦听器已连接的元素)和
  2. event.target ,它是事件实际发生的元素

这些可以是相同的元素,父母和子女,或祖先和后代(这里就是这种情况)。



在LI上使它成为 target ,并且由于body的click处理程序调用了监听器,它是 currentTarget ,DIV既不是。如果将侦听器放在DIV上,它将成为 currentTarget



最初,元素之外的其他节点可能是事件目标,但在最近的实现中,只有元素是目标。



一些链接:
$ b


  1. W3C DOM 4接口eventTarget

  2. W3C DOM 4 Event

请注意, target eventTarget 被指定为(主机)对象,但它们不一定是元素,但它们主要是如何实现的目前的浏览器。

I'm trying to create one event listener to handle all my "clicks" by putting it on the body and doing some event delegation. A simple example of what i'm trying to do is this:

<html>
 <body> 
  <div id = "div1">
   <ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
   <ul>
  </div>
   <script>
    document.body.addEventListener('click', function(e){
     if(e.target.id == "div1"){alert("hi")}
    })
   </script>
 </body>
</html>

What I expect from the code above is that when I click on the "li" elements, the alert would fire since it is nested within the parent div. I thought that the event would propagate to the parent and fire. However, it doesn't seem to be working at all if I click on the li elements. Can someone help explain what's happening? Thank you!

If i was to do it the normal way by adding the eventListener directly to the div id, it would then work.

解决方案

There are two elements associated with an event:

  1. event.currentTarget, which is the element that is actually calling the listener (i.e. the on which the listener has been attached), and
  2. event.target, which is the element on which the event actually occurred

These can be the same element, parent and child, or ancestor and descendant (which is the case here).

So a click on an LI makes it the target, and since the body's click handler calls the listener, it's the currentTarget, the DIV is neither. If you put the listener on the DIV, it will then become the currentTarget.

Originally, nodes other than elements could be event targets, but in recent implementations only elements are targets.

Some links:

  1. W3C DOM 4 Interface eventTarget
  2. W3C DOM 4 Event

Note that that target and eventTarget are specified as (host) objects, they aren't necessarily elements though that is how they are mostly implemented in current browsers.

这篇关于点击时的Javascript事件监听器无法按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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