[英]How can it be that I can access and use event.currentTarget but when I print the event then currentTarget is 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);
}
我認為currentTarget在html中沒有“可用”2年(我曾經是as3開發人員)。現在我試着找出它為什么不“可用”,但是當我找到這個引用MDN Event.target時 , e.currentTarget顯示了一個對象,讓我很困惑。現在對我來說當前目標'可用',它讓我的生活變得更輕松,但我只是想知道為什么控制台騙我
問題是標簽是動態生成的 ,因此您必須提升范圍,並將事件偵聽器附加到非動態生成的元素 。
這是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>
由於document
始終可用,因此它始終會附加偵聽器。 然后,在應用點擊事件之前,它只是“等待”創建動態元素。
我也在這里創造了一個小提琴。
希望這可以幫助! :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.