using Dojo to programmaticaly add a list of images and add a click event for each of them

隐身守侯 提交于 2019-12-12 02:19:17

问题


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>

回答1:


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.

Example: https://jsfiddle.net/an90dr/493khnug/



来源:https://stackoverflow.com/questions/37418651/using-dojo-to-programmaticaly-add-a-list-of-images-and-add-a-click-event-for-eac

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!