I’m creating a table with images using jQuery. My js code looks like this:
$(document).ready(function() {
var korpusArray = new Array();
$.getJSON("file.js", function(data) {
var korpusId;
var korpusChooseTable = "<table id='TableKorpusGaleria'><tbody><tr>";
$.each(data, function(i, value) {
korpusArray.push(value.text);
strRemove = value.filename.replace("korpus/", "");
korpusChooseTable += '<td><p>'+value.title+'</p><p style="display:none;">'+value.id+'</p></br><img src="/korpus/thumbs/phoca_thumb_s_'+strRemove+'"></td>';
});
korpusChooseTable += '</tr></tbody></table>';
$("#korpusChoose").html(korpusChooseTable);
console.log(korpusArray.length);
console.log(data.length);
});
// after this I wanna click on table cell and do some function but
// it doesnt work. Can somebody tell me what I'm doing wrong?
$("#korpusChoose #TableKorpusGaleria tbody td").click(function() {
alert();
});
});
Use delegation for dynamically created items – if the element does not exist at the time of binding… which is usually at dom ready – then no event handlers will be attached
jQuery 1.7 and up http://api.jquery.com/on/
or jQuery 1.6 down to jQuery 1.4.3 http://api.jquery.com/delegate/
Another way would be to add right after you add it to the dom
then right after
Though the latter is less efficient since you would be binding an event handler to every td element in the table – using delegation you only bind it to a parent element which exists in the dom and will handle the event when it bubbles up