fli*_*ips 5 javascript javascript-events
在下面的代码中,您将看到我正在尝试为image.onclick定义一个事件处理程序,它需要额外的参数,我在while循环中声明了这些参数,希望javascript定义范围这样,但事实并非如此.基本上这里的所有事件处理程序都获得了我给变量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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
aps*_*ers 14
关闭解决了另一个问题!
image.onclick = function(id, section_id){
return function(event) {
deleteImage(event,id,section_id);
}
}(id, section_id);
Run Code Online (Sandbox Code Playgroud)
外部函数立即运行(注意末尾带有参数的括号),并返回内部函数,该函数在其范围内保留变量的副本,就像它们在循环的迭代中一样.
JavaScript的按值传递非对象变量,通过传递id和section_id外部函数,在创建它们的副本该函数内部.当您创建并返回内部函数,即内部函数保存的范围是在其创作的时间范围内的所有变量(这是在的心脏封闭是什么),包括局部变量副本id和section_id.内部函数及其唯一范围成为该元素的事件处理程序.