情况有点像
var someVar = some_other_function();
someObj.addEventListener("click", function(){
some_function(someVar);
}, false);
问题是someVar的值在addEventListener的侦听器函数中是不可见的,在addEventListener中它可能被视为一个新变量。
情况有点像
var someVar = some_other_function();
someObj.addEventListener("click", function(){
some_function(someVar);
}, false);
问题是someVar的值在addEventListener的侦听器函数中是不可见的,在addEventListener中它可能被视为一个新变量。
当前回答
这里还有另一种方法(它在for循环中工作):
var someVar = some_other_function();
someObj.addEventListener("click",
function(theVar){
return function(){some_function(theVar)};
}(someVar),
false);
其他回答
这个问题很老了,但我想我可以使用ES5的.bind()为后代提供一个替代方案。:)
function some_func(otherFunc, ev) {
// magic happens
}
someObj.addEventListener("click", some_func.bind(null, some_other_func), false);
请注意,您需要设置listener函数,将第一个参数作为传递给bind(您的另一个函数)的参数,第二个参数现在是事件(而不是第一个,因为它本来就是)。
不错的一行选择
element.addEventListener('dragstart',(evt) => onDragStart(param1, param2, param3, evt));
function onDragStart(param1, param2, param3, evt) {
//some action...
}
向eventListener的回调函数发送参数需要创建一个隔离函数并将参数传递给该隔离函数。
这里有一个很好的辅助函数。基于上面“hello world”的例子。)
还有一件事是维护对函数的引用,这样我们就可以干净地删除侦听器。
// Lambda closure chaos.
//
// Send an anonymous function to the listener, but execute it immediately.
// This will cause the arguments are captured, which is useful when running
// within loops.
//
// The anonymous function returns a closure, that will be executed when
// the event triggers. And since the arguments were captured, any vars
// that were sent in will be unique to the function.
function addListenerWithArgs(elem, evt, func, vars){
var f = function(ff, vv){
return (function (){
ff(vv);
});
}(func, vars);
elem.addEventListener(evt, f);
return f;
}
// Usage:
function doSomething(withThis){
console.log("withThis", withThis);
}
// Capture the function so we can remove it later.
var storeFunc = addListenerWithArgs(someElem, "click", doSomething, "foo");
// To remove the listener, use the normal routine:
someElem.removeEventListener("click", storeFunc);
您编写的代码绝对没有任何问题。some_function和someVar都应该是可访问的,以防它们在匿名的上下文中可用
function() { some_function(someVar); }
被创建。
检查警报是否为您提供了您一直在寻找的值,确保它可以在匿名函数的作用域内访问(除非您在addEventListener调用旁边有更多操作相同someVar变量的代码)
var someVar;
someVar = some_other_function();
alert(someVar);
someObj.addEventListener("click", function(){
some_function(someVar);
}, false);
可能不是最优的,但对于那些不精通js的人来说已经足够简单了。将调用addEventListener的函数放到它自己的函数中。通过这种方式,传递给它的任何函数值都保持自己的作用域,并且您可以尽可能多地迭代该函数。
示例我与文件读取,因为我需要捕捉和渲染图像和文件名的预览。在使用多文件上传类型时,我花了一段时间来避免异步问题。尽管上传了不同的文件,我还是会意外地在所有渲染中看到相同的“名称”。
最初,所有的readFile()函数都在readFiles()函数中。这导致了异步作用域问题。
function readFiles(input) {
if (input.files) {
for(i=0;i<input.files.length;i++) {
var filename = input.files[i].name;
if ( /\.(jpe?g|jpg|png|gif|svg|bmp)$/i.test(filename) ) {
readFile(input.files[i],filename);
}
}
}
} //end readFiles
function readFile(file,filename) {
var reader = new FileReader();
reader.addEventListener("load", function() { alert(filename);}, false);
reader.readAsDataURL(file);
} //end readFile