Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save emahiro/9a2ba00a3fdd9c1fc66d to your computer and use it in GitHub Desktop.
Save emahiro/9a2ba00a3fdd9c1fc66d to your computer and use it in GitHub Desktop.
sample.js
/**
* forの中のiはevent内部の関数からみたらグローバル変数になるので、forで最後まで回した値がchangeの中に入ってしまう。
*/
// 即時関数を使う
for (var i = 0; i < targetElArray.length; i++) {
(function(_i){
$('#' + targetElArray[_i]).change(function(event) {
console.log(targetElArray[_i]);
handleUploading(event, this.id);
});
})(i);
}
// this要素を使う
for (var i = 0; i < targetElArray.length; i++) {
$('#' + targetElArray[_i]).change(function(event) {
console.log(this.id);
handleUploading(event, this.id);
});
}
@emahiro
Copy link
Author

emahiro commented Mar 18, 2016

即時関数の場合はchange関数に対して引数 i 渡していて、change関数内部では _i として扱う

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment