情况有点像
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中它可能被视为一个新变量。
当前回答
向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);
其他回答
你可以用'bind'绑定所有必要的参数:
root.addEventListener('click', myPrettyHandler.bind(null, event, arg1, ... ));
通过这种方式,您将始终获得事件、arg1和其他传递给myPrettyHandler的东西。
http://passy.svbtle.com/partial-application-in-javascript-using-bind
在所有函数中都有一个特殊的变量:参数。您可以将参数作为匿名参数传递,并通过arguments变量(按顺序)访问它们。
例子:
var someVar = some_other_function();
someObj.addEventListener("click", function(someVar){
some_function(arguments[0]);
}, false);
$form.addEventListener('submit', save.bind(null, data, keyword, $name.value, myStemComment));
function save(data, keyword, name, comment, event) {
这就是我如何正确地传递事件。
function. prototype.bind()是将目标函数绑定到特定作用域并可选地在目标函数中定义this对象的方法。
someObj.addEventListener("click", some_function.bind(this), false);
或者捕获一些词法范围,例如在循环中:
someObj.addEventListener("click", some_function.bind(this, arg1, arg2), false);
最后,如果目标函数中不需要this参数:
someObj.addEventListener("click", some_function.bind(null, arg1, arg2), false);
也可以试试这些(IE8 + Chrome。我不知道FF):
function addEvent(obj, type, fn) {
eval('obj.on'+type+'=fn');
}
function removeEvent(obj, type) {
eval('obj.on'+type+'=null');
}
// Use :
function someFunction (someArg) {alert(someArg);}
var object=document.getElementById('somObject_id') ;
var someArg="Hi there !";
var func=function(){someFunction (someArg)};
// mouseover is inactive
addEvent (object, 'mouseover', func);
// mouseover is now active
addEvent (object, 'mouseover');
// mouseover is inactive
希望没有拼写错误:-)