将动态onclick事件设置为图像列表

时间:2014-02-19 02:12:15

标签: javascript

我有这个示例代码,其中我有一组图像,我创建了dinamically并设置为每个具有某些参数的onclick addlistener。 问题是,当设置onclick时,所有这些弹出窗口始终是最后一个图像的值。

任何想法为什么我不能单独和dinamycally设置每个人的听众?

感谢。

以下功能齐全的代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title></title>
    <script type="text/javascript">

function image() {
var shared = eval([{"img":"9","ext":"jpg"},{"img":"8","ext":"jpg"},{"img":"20","ext":"jpg"},{"img":"24","ext":"png"}]);
var divShared = document.getElementById('image');
for(x in shared){         
   var img = document.createElement("img");
   img.id = "img_"+shared[x].img;
   img.style.width = "30px";
   img.style.height = "30px";
   img.style.cursor = "pointer";
   img.style.marginLeft = "15px";
   var url = "http://www.kakuylive.com/fotos/user_"+shared[x].img+"."+shared[x].ext;
   img.src = url;    
   document.getElementById('image').appendChild(img);                          
   document.getElementById("img_"+shared[x].img).addEventListener('click', function() { openSharedUserInfo(shared[x].img,shared[x].ext)},false);  
}
}

function openSharedUserInfo(id,ext){
  alert(id+" :: "+ext);
}
</script>
</head>

<body>
<div id="image" style="margin-bottom:15px"></div>
<div><a href="javascript:image();">click to see image</a></div>
</body>
</html>

1 个答案:

答案 0 :(得分:2)

注意立即调用的函数(IIFE)作为循环代码的第一行,它将为您提供额外的“级别”范围,以便您引用的x将是您认为的那个当事件发生时。

这是一个经典的闭包问题,见here。下面的代码应该可以解决您遇到的问题。

for (x in shared) {
   (function(x) {
      var img = document.createElement("img");
      img.id = "img_" + shared[x].img;
      img.style.width = "30px";
      img.style.height = "30px";
      img.style.cursor = "pointer";
      img.style.marginLeft = "15px";
      var url = "http://www.kakuylive.com/fotos/user_" + shared[x].img + "." + shared[x].ext;
      img.src = url;
      document.getElementById('image').appendChild(img);
      document.getElementById("img_" + shared[x].img).addEventListener('click', function() {
         openSharedUserInfo(shared[x].img, shared[x].ext)
      }, false);
   }(x))
}

function openSharedUserInfo(id, ext) {
   alert(id + " :: " + ext);
}

其他注释

循环数组时,不应该使用for in循环;出于性能原因,首选标准for循环。您不需要再次执行getElementById,因为您已经在手边拥有了DOM元素,因为您正在此函数中创建它。

相关问题