情况有点像
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中它可能被视为一个新变量。
当前回答
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);
在我的项目中完美地工作。希望这能有所帮助
其他回答
someevar值应该只能在some_function()上下文中访问,而不能从侦听器的上下文中访问。 如果你想在监听器中拥有它,你必须这样做:
someObj.addEventListener("click",
function(){
var newVar = someVar;
some_function(someVar);
},
false);
并使用newVar代替。
另一种方法是从some_function()返回someVar值,以便在监听器中进一步使用它(作为一个新的本地变量):
var someVar = some_function(someVar);
下面的答案是正确的,但如果你使用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文件的人有用。
祝你好运! !
一种方法是用一个外部函数:
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));
下面的方法对我很有效。从这里修改。
函数回调(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 >
如果我没有弄错的话,使用bind调用函数实际上创建了一个由bind方法返回的新函数。这将在以后给你带来问题,或者如果你想删除事件监听器,因为它基本上就像一个匿名函数:
// Possible:
function myCallback() { /* code here */ }
someObject.addEventListener('event', myCallback);
someObject.removeEventListener('event', myCallback);
// Not Possible:
function myCallback() { /* code here */ }
someObject.addEventListener('event', function() { myCallback });
someObject.removeEventListener('event', /* can't remove anonymous function */);
记住这一点。
如果你正在使用ES6,你可以按照建议做,但更干净一点:
someObject.addEventListener('event', () => myCallback(params));