使用Dojo进行程序设计,添加一个图像列表,并为每个图像添加一个点击事件 [英] using Dojo to programmaticaly add a list of images and add a click event for each of them

查看:126
本文介绍了使用Dojo进行程序设计,添加一个图像列表,并为每个图像添加一个点击事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Dojo加载图像列表并添加一个点击事件,所以当用户单击图像时,会显示该图像的ID。请看下面的代码。图像被加载,但是当我点击它们时,只有'10143'写在日志中。任何想法为什么发生了?请帮助!

I am loading a list of images and adding a click event to each of them using Dojo so when user clicks an image, the ID for that image gets displayed. Please see codes below. Images were loaded, but when I click each of them, only '10143' was written in the log. any ideas why that happened? Please help!

var PictureIds = ['10141', '10142', '10143'];
var resultUl = domConstruct.create('ul');
for (i = 0; i < PictureIds.length; i++){
  var image= domConstruct.create('img', {
    id: PictureIds[i],
    src: "./images/"+ PictureIds[i] + ".jpg",
    class: "photo"});

  var li= domConstruct.create('li');
  domConstruct.place(image, li);
  domConstruct.place(li, resultUl);

  on(image, 'click', function(){
    console.log(image.id);
  });
}
domConstruct.place(resultUl,'pictures');

<div id="pictures"></div>

推荐答案

我建议使用 dojo / array 而不是for循环。此外,您应该在代码开始时创建图像。然后将它们添加到数组中,并在该数组上进行循环,以将其添加到dom。

I would suggest to use dojo/array instead of for loop. Also you should create your images at the beggining of your code. Then add them in an array and make a loop on that array in order to add them to the dom.

下面给出一个例子,但为了简单起见,我使用段落标签而不是图像。
您可以在下面的示例中做我所做的工作,而不是创建可以创建图像的段落。

I am giving an example below but I am using paragraph tags instead of images for simplicity. You can do what I am doing on the example below but instead of creating paragraphs you can create images.

示例: https://jsfiddle.net/an90dr/493khnug/

这篇关于使用Dojo进行程序设计,添加一个图像列表,并为每个图像添加一个点击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆