如何将parameter passing给addEventListener监听器函数?
情况有点像 –
var someVar = some_other_function(); someObj.addEventListener("click", function(){ some_function(someVar); }, false);  问题是someVar的值在addEventListener的监听器函数内部是不可见的,在那里它可能被当作一个新的variables来处理。 
 你写的代码绝对没有错。  some_function和someVar都应该可以访问,以防匿名的情况下可用 
 function() { some_function(someVar); } 
被创build。
 检查警报是否提供了您一直在寻找的值,确保它可以在匿名函数的范围内访问(除非您有更多的代码在对addEventListener的调用旁边运行相同的someVarvariables) 
 var someVar; someVar = some_other_function(); alert(someVar); someObj.addEventListener("click", function(){ some_function(someVar); }, false); 
为什么不直接从事件的目标属性获取参数?
例:
 var someInput = document.querySelector('input'); someInput.addEventListener('click', myFunc, false); someInput.myParam = 'This is my parameter'; function myFunc(evt) { window.alert( evt.target.myParam ); } 
JavaScript是面向原型的语言,请记住!
这个问题是古老的,但我想我会提供一个替代使用ES5的.bind() – 为后代。 🙂
 function some_func(otherFunc, ev) { // magic happens } someObj.addEventListener("click", some_func.bind(null, some_other_func), false); 
要知道,你需要设置你的监听器函数,第一个参数作为你传递给bind的参数(你的其他函数),第二个参数现在是事件(而不是第一个,因为它会是) 。
您可以通过将函数声明为variables来添加和删除带有参数的eventlisteners。
 myaudio.addEventListener('ended',funcName=function(){newSrc(myaudio)},false); 
  newSrc是myaudio作为参数的方法funcName是函数名称variables 
 您可以使用myaudio.removeEventListener('ended',func,false);删除监听器myaudio.removeEventListener('ended',func,false); 
  someVar值只能在some_function()上下文中访问,而不能从listener的上下文中访问。 如果你喜欢把它放在监听器中,你必须做如下的事情: 
 someObj.addEventListener("click", function(){ var newVar = someVar; some_function(someVar); }, false); 
 并使用newVar 。 
 另一种方法是从some_function()返回someVar值,以便在侦听器中进一步使用它(作为新的本地variables): 
 var someVar = some_function(someVar); 
你可以通过一个JavaScript函数(被称为闭包 )通过value(而不是引用)传递somevar:
 var someVar='before'; func = function(v){ console.log(v); } document.addEventListener('click',function(someVar){ return function(){func(someVar)} }(someVar)); someVar='after' 
 或者你可以写一个通用的包装函数,如wrapEventCallback : 
 function wrapEventCallback(callback){ var args = Array.prototype.slice.call(arguments, 1); return function(e){ callback.apply(this, args) } } var someVar=1; func = function(v){ console.log(v); } document.addEventListener('click',wrapEventCallback(func,someVar)) someVar='after' 
还有另一种方法(这个在循环里面工作):
 var someVar = some_other_function(); someObj.addEventListener("click", function(theVar){ return function(){some_function(theVar)}; }(someVar), false); 
使用
  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); 
在我的项目中完美的工作。 希望这会有所帮助
也试试这些(IE8 +铬我不知道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 
希望没有错别字:-)
相当古老的问题,但今天我有同样的问题。 我find的最干净的解决scheme是使用柯里化的概念。
代码为:
 someObj.addEventListener('click', some_function(someVar)); var some_function = function(someVar) { return function(e) { // do something here } } 
你可以用“绑定”绑定所有必要的参数:
 root.addEventListener('click', myPrettyHandler.bind(null, event, arg1, ... )); 
通过这种方式,您将始终获得传递给myPrettyHandler的事件arg1和其他内容。
http://passy.svbtle.com/partial-application-in-javascript-using-bind
将参数发送到eventListener的callback函数需要创build一个独立的函数并将parameter passing给该独立函数。
这里有一个很好用的小助手function。 基于上面的“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); 
一种方法是用一个外部函数做这个:
 elem.addEventListener('click', (function(numCopy) { return function() { alert(numCopy) }; })(num)); 
这种将括号内的匿名函数包装起来并立即调用的方法称为IIFE (Immediately-Invoked Function Expression)
你可以在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)); 
我被困在这个,因为我在循环中使用它来查找元素并添加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); }); } 
  var EV = { ev: '', fn: '', elem: '', add: function () { this.elem.addEventListener(this.ev, this.fn, false); } }; function cons() { console.log('some what'); } EV.ev = 'click'; EV.fn = cons; EV.elem = document.getElementById('body'); EV.add(); //If you want to add one more listener for load event then simply add this two lines of code: EV.ev = 'load'; EV.add(); 
下面的方法适合我。 从这里修改。
 function callback(theVar) { return function() { theVar(); } } function some_other_function() { document.body.innerHTML += "made it."; } var someVar = some_other_function; document.getElementById('button').addEventListener('click', callback(someVar)); 
 <!DOCTYPE html> <html> <body> <button type="button" id="button">Click Me!</button> </body> </html> 
尝试这个
 someObj.addEventListener("click", function(){ some_function(someVar); }.bind(this) ); 
其他的select,也许不像使用绑定那样优雅,但是它对循环中的事件是有效的
 for (var key in catalog){ document.getElementById(key).my_id = key document.getElementById(key).addEventListener('click', function(e) { editorContent.loadCatalogEntry(e.srcElement.my_id) }, false); } 
它已经过谷歌浏览器扩展的testing,也许e.srcElement必须被其他浏览器中的e.source所取代
我发现这个解决scheme使用Imatoria 发表的评论 ,但是我不能把它标记为有用,因为我没有足够的声望:D
下面的答案是正确的,但如果您使用yuicompressor压缩了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文件的人来说是有用的。
祝你好运!!
下面的代码对我来说很好(firefox):
 for (var i=0; i<3; i++) { element = new ... // create your element element.counter = i; element.addEventListener('click', function(e){ console.log(this.counter); ... // another code with this element }, false); } 
输出:
 0 1 2 
所有函数中都有一个特殊的variables: 参数 。 您可以将参数作为匿名parameter passing,并通过参数variables访问它们(按顺序)。
例:
 var someVar = some_other_function(); someObj.addEventListener("click", function(someVar){ some_function(arguments[0]); }, false);