以下のコードでは、追加のパラメーターを受け取る image.onclick のイベント ハンドラーを定義しようとしていることがわかります。JavaScript がこのようにスコープを定義することを期待して while ループ内でこれらのパラメーターを宣言していましたが、そうではありません。基本的に、ここにあるすべてのイベント ハンドラーは、変数 id と section_id に与える最後の値を取得しています。これらのハンドラーを動的に生成したい状況を処理する方法についてのアイデアはありますか?
function handlePicturesResult(){
if (req.readyState == 4) { // Complete
if (req.status == 200) { // OK response
var el = document.getElementById('pictureHolder');
while( el.hasChildNodes() ){
el.removeChild(el.lastChild);
}
var tempObject = JSON.parse(req.responseText);
var pictures = tempObject.images;
var i=0;
while(i<pictures.length){
var picIndex = i;
var image= new Image(120,80);
image.src = 'images/' + pictures[i].url;
image.width = 120;
image.height = 80;
var id = pictures[picIndex].id;
var section_id = pictures[picIndex].sectionId;
image.onclick = function(event){
deleteImage(event,id,section_id);
}
var txtNode = document.createTextNode(pictures[picIndex.valueOf()].id);
el.appendChild(image);
el.appendChild(txtNode);
i++;
}
} else {
alert("Problem: " + req.statusText);
}
}
}