如何传递参数给addEventListener监听器函数? [英] How to pass arguments to addEventListener listener function?

查看:185
本文介绍了如何传递参数给addEventListener监听器函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

情况有点像 -

var someVar = some_other_function();
someObj.addEventListener("click", function(){
    some_function(someVar);
}, false);

问题是 someVar addEventListener 的监听器函数内不可见,在这个函数可能被视为一个新变量。

The problem is that the value of someVar is not visible inside the listener function of the addEventListener, where it is probably being treated as a new variable.

推荐答案

你写的代码完全没有错。应该可以访问 some_function someVar ,以防在匿名

There is absolutely nothing wrong with the code you've written. Both some_function and someVar should be accessible, in case they were available in the context where anonymous

function() { some_function(someVar); } 

已创建。

检查警报是否提供您一直在寻找的价值,请确保它在匿名功能的范围内可以访问(除非您有更多的代码可以运行在调用 addEventListener 之前的同一个 someVar 变量上)

Check if the alert gives you the value you've been looking for, be sure it will be accessible in the scope of anonymous function (unless you have more code that operates on the same someVar variable next to the call to addEventListener)

var someVar; 
someVar = some_other_function();
alert(someVar);
someObj.addEventListener("click", function(){
    some_function(someVar);
}, false);

这篇关于如何传递参数给addEventListener监听器函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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