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

查看:40
本文介绍了如何将参数传递给 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_functionsomeVar 都应该是可访问的,以防它们在匿名

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); } 

已创建.

检查警报是否为您提供了您一直在寻找的值,确保它可以在匿名函数的范围内访问(除非您有更多代码对同一 someVar 变量进行操作在对 addEventListener) 的调用旁边)

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天全站免登陆