Try this, you need to use on() and delegate on the closest static parent element for dynamically added elements
$(document).on('click','.photo',function(){
alert('Works!');
});
Frage
I have to use dynamically created images for my projekt. I do this with jQuery:
var img = $('<img />').attr({ 'id': i, 'src': e.files[i].thumbnails["200x200"], 'alt':e.files[i].name, 'class': 'photo'}).appendTo($('#img'));
But I can't run a function if the image is clicked. I tried:
$(document).ready(function() {
$(".photo").click(function(){
alert('Works!');
});
};
and onClick:
var img = $('<img />').attr({ 'id': i, 'src': e.files[i].thumbnails["200x200"], 'alt':e.files[i].name, 'class': 'photo', 'onClick': 'test();' }).appendTo($('#img'));
[...]
function test(){
alert('Works!');
}
But both ways aren't working... What did I wrong?
Lösung
Try this, you need to use on() and delegate on the closest static parent element for dynamically added elements
$(document).on('click','.photo',function(){
alert('Works!');
});
Andere Tipps
When you do
$(".photo").click(function(){
alert('Works!');
});
it is only binding it to the elements in the dom, so once you add dynamic html, it doesn't bind that even to that html. In that case if you use
$(document).on('click','.photo',function(){
alert('Works');
});
This code would bind the click event to every element in html even if it is added dynamically.
Just add the event handler when creating the image?
var img = $('<img>')
.attr({
id: i,
src: e.files[i].thumbnails["200x200"],
alt: e.files[i].name,
// keep 'class' for jshint
'class': 'photo'
})
.click(function () {
alert('Works!');
})
// you can leave out $('#img') and just write:
.appendTo('#img');
of course you should define that click handler function only once:
function clickHandler() { // do stuff }
and add it like .click(clickHandler)
in the example above.