简体   繁体   English

为什么html event.currentTarget在您登录时为null

[英]why html event.currentTarget is null when you log

function hide (e){
    console.log(e);//but in the Console click on triangle the currentTarget is null,why?
    console.log(e.currentTarget) //is an object.
}
var ps = document.getElementsByTagName('p');

for(var i = 0; i < ps.length; i++){
    ps[i].addEventListener('click', hide, false);
}

i thought the currentTarget is not 'available' in html for 2 years(i used to be as3 developer).just right now i try to find out why it not 'available',but when i find this reference MDN Event.target ,the e.currentTarget shows a object,that confused me.now with the currentTarget 'available' for me,it make my life easier,but i just want to know why console lie to me 我认为currentTarget在html中没有“可用”2年(我曾经是as3开发人员)。现在我试着找出它为什么不“可用”,但是当我找到这个引用MDN Event.target时 , e.currentTarget显示了一个对象,让我很困惑。现在对我来说当前目标'可用',它让我的生活变得更轻松,但我只是想知道为什么控制台骗我

The problem is that the tags are dynamically-generated , so you have to hoist the scope, and attach the event listener to an element that is not dynamically generated . 问题是标签是动态生成的 ,因此您必须提升范围,并将事件侦听器附加到非动态生成元素

Here's an example with jQuery, attaching the listener to document : 这是jQuery的一个例子,将监听器附加到document

 $(document).on("click", "p", function(e) { console.log(e.currentTarget); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p> One </p> <p> Two </p> <p> Three </p> 

Because document is always available, it will always have the listener attached. 由于document始终可用,因此它始终会附加侦听器。 It then simply 'waits' for the dynamic elements to be created, before applying their click events. 然后,在应用点击事件之前,它只是“等待”创建动态元素。

I've also created a fiddle demonstrating this here . 我也在这里创造了一个小提琴。

Hope this helps! 希望这可以帮助! :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM