情况有点像
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中它可能被视为一个新变量。
当前回答
一种方法是用一个外部函数:
elem.addEventListener('click', (function(numCopy) {
return function() {
alert(numCopy)
};
})(num));
这种将匿名函数包装在圆括号中并立即调用它的方法称为IIFE(立即调用函数表达式)。
您可以在http://codepen.io/froucher/pen/BoWwgz中查看带有两个参数的示例。
catimg.addEventListener('click', (function(c, i){
return function() {
c.meows++;
i.textContent = c.name + '\'s meows are: ' + c.meows;
}
})(cat, catmeows));
其他回答
这里还有另一种方法(它在for循环中工作):
var someVar = some_other_function();
someObj.addEventListener("click",
function(theVar){
return function(){some_function(theVar)};
}(someVar),
false);
为什么不直接从事件的目标属性获取参数呢?
例子:
const someInput = document.querySelector('button'); someInput。addEventListener('click', myFunc, false); someInput。myParam = '这是我的参数'; 函数myFunc (evt) { window.alert (evt.currentTarget.myParam); } <button class="input">显示参数</button>
JavaScript是一种面向原型的语言,记住!
这是个老问题了,但我今天也遇到了同样的问题。我发现的最干净的解决方法是使用咖喱的概念。
它的代码是:
someObj.addEventListener('click', some_function(someVar));
var some_function = function(someVar) {
return function curried_func(e) {
// do something here
}
}
通过命名curry函数,可以调用Object。removeEventListener在以后的执行时间取消注册eventListener。
下面的方法对我很有效。从这里修改。
函数回调(theVar) { 返回函数(){ theVar (); } } 函数some_other_function() { document.body.innerHTML += "made it."; } var someVar = some_other_function; . getelementbyid(“按钮”)。addEventListener(“点击”,回调(someVar)); <!DOCTYPE html > < html > 身体< > <button type="button" id="button">点击我!< / >按钮 < /身体> < / html >
Use
el.addEventListener('click',
function(){
// this will give you the id value
alert(this.id);
},
false);
如果你想传递任何自定义值到这个匿名函数那么最简单的方法是
// this will dynamically create property a property
// you can create anything like el.<your variable>
el.myvalue = "hello world";
el.addEventListener('click',
function(){
//this will show you the myvalue
alert(el.myvalue);
// this will give you the id value
alert(this.id);
},
false);
在我的项目中完美地工作。希望这能有所帮助