Javascript传递值以在事件侦听器上运行

Gue*_*ser 1 javascript

如果我执行以下操作,变量将传递给附加的事件侦听器,其中我想要在添加事件侦听器时传递变量的值.

foo=a;    
document.addEventListener('mousedown', function() { doSomething(foo) }, false); 
foo=b;

doSomething(val){
alert(val);
}
Run Code Online (Sandbox Code Playgroud)

所以它应警告"a"而不是"b";

Yos*_*shi 7

就像是:

var foo = 'a';    

document
.getElementById('foo')
.addEventListener('click', function(bar) {

  // return the actual event handler function
  return function() {
    doSomething(bar);
  };

}(foo) /* <-- call the anonymous function, passing in the current foo*/, false); 

foo = 'b';

function doSomething (val) {
  alert(val);
}?
Run Code Online (Sandbox Code Playgroud)

演示:http://jsfiddle.net/gS9wu/1/