简体   繁体   English

如何为此使用addEventListener?

[英]How to use addEventListener for this?

I am trying to add an event listener to child divs within a container div. 我正在尝试向容器div中的子div添加事件侦听器。 I am having an issue with figuring out how to do this properly. 我在弄清楚如何正确执行此操作时遇到问题。 The code I have so far is here: pastebin . 到目前为止,我的代码在这里: pastebin The listener (click) is on line 35 侦听器(单击)在第35行

You're calling the context function instead of passing it as a listener. 您正在调用context函数,而不是将其作为侦听器传递。 I mean, this: 我的意思是:

divs[i].addEventLisenter('click', context(divs[i].id), true);

should be: 应该:

divs[i].addEventLisenter('click', context, true);

And this: 和这个:

function context(id) {
    console.log(id+' clicked');
}

should be: 应该:

function context(evt) {
    console.log(this.id + ' clicked');
}

JavaScript是经过解释的,因此您应该将docINIT的定义移至其使用之上。

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

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