如果我执行以下操作,变量将传递给附加的事件侦听器,其中我想要在添加事件侦听器时传递变量的值.
foo=a;
document.addEventListener('mousedown', function() { doSomething(foo) }, false);
foo=b;
doSomething(val){
alert(val);
}
Run Code Online (Sandbox Code Playgroud)
所以它应警告"a"而不是"b";
就像是:
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/
| 归档时间: |
|
| 查看次数: |
1645 次 |
| 最近记录: |