情况有点像
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中它可能被视为一个新变量。
当前回答
下面的答案是正确的,但如果你使用yuiccompressor压缩js文件,下面的代码在IE8中不能工作。(事实上,大多数美国人仍然在使用IE8)
var someVar;
someVar = some_other_function();
alert(someVar);
someObj.addEventListener("click",
function(){
some_function(someVar);
},
false);
所以,我们可以修复上面的问题如下,它在所有浏览器工作良好
var someVar, eventListnerFunc;
someVar = some_other_function();
eventListnerFunc = some_function(someVar);
someObj.addEventListener("click", eventListnerFunc, false);
希望对在生产环境下压缩js文件的人有用。
祝你好运! !
其他回答
我被困在这里,因为我在循环中使用它来查找元素并向它添加listner。如果你在循环中使用它,那么这将完美地工作
for (var i = 0; i < states_array.length; i++) {
var link = document.getElementById('apply_'+states_array[i].state_id);
link.my_id = i;
link.addEventListener('click', function(e) {
alert(e.target.my_id);
some_function(states_array[e.target.my_id].css_url);
});
}
如果以后想要删除事件侦听器,那么创建对curry函数的引用是一个不错的选择。
在下面的代码中,我将说明我的意思。
// This is the curry function. We return a new function with the signature of what the click-listener expects
const handleClick = (foo, bar) => (clickEvent) => {
console.log('we get our custom input', foo, bar);
console.log('we get the click event too', clickEvent);
}
// We need to store a reference to the listener, making sure we are removing the correct reference later
const myListener = handleClick('foo', 'bar'); // Remember that we now return the actual event-handler
const btn = document.getElementById('btn'); // find the element to attach the listener to
btn.addEventListener('click', myListener);
// remove the event listener like this by using our reference
btn.removeEventListener('click', myListener);
下面是CodePen上的一个工作示例
你可以用'bind'绑定所有必要的参数:
root.addEventListener('click', myPrettyHandler.bind(null, event, arg1, ... ));
通过这种方式,您将始终获得事件、arg1和其他传递给myPrettyHandler的东西。
http://passy.svbtle.com/partial-application-in-javascript-using-bind
这个解决方案可能很好看
var some_other_function = someVar => function() {
}
someObj.addEventListener('click', some_other_function(someVar));
或者绑定变量也不错
这里还有另一种方法(它在for循环中工作):
var someVar = some_other_function();
someObj.addEventListener("click",
function(theVar){
return function(){some_function(theVar)};
}(someVar),
false);