问题
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