简体   繁体   English

将值传递给 eventListener 函数

[英]Passing value to eventListener functions

for ( var i=0; i<thumbs.length; i++) {
    var num = i;
    Core.addEventListener(thumbs[i], "click",  Slide.thumbClick);
}

In the above code, I want to pass the value of var num to the thumbClick eventlistener.在上面的代码中,我想将var num的值传递给thumbClick but I am unable to.但我做不到。 If I try to display that value, it gives an undefined value.如果我尝试显示该值,它会给出一个未定义的值。 pls help请帮忙

Don't remember for sure, but you should be able to do something like this:不记得了,但你应该能够做这样的事情:

Core.addEventListener(thumbs[i], "click", function() {
    //...do stuff here
});

var num should still be available to this anonymous function.这个匿名函数应该仍然可以使用 var num

One way to do it would be to create a dynamic function.一种方法是创建一个动态函数。

Something like this.像这样的东西。 (I'm basing this on my experience with other ECMAScript-based languages, you might want to double-check to make sure this works.) (我基于我使用其他基于 ECMAScript 的语言的经验,您可能需要仔细检查以确保它有效。)

for ( var i=0; i<thumbs.length; i++)
{
        var num = i;
        Core.addEventListener(thumbs[i], "click",  new function(evt){
            Slide.thumbClick(num);
        });
}

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

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