Skip to content Skip to sidebar Skip to footer

Can't Click On The Table Created With Jquery

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)

Solution 1:

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/

$("#korpusChoose ").on('click','#TableKorpusGaleria tbody td',function(){
       alert();       
});

or jQuery 1.6 down to jQuery 1.4.3 http://api.jquery.com/delegate/

$("#korpusChoose ").delegate('#TableKorpusGaleria tbody td','click',function(){
       alert();       
});

Rewriting the .live() method in terms of its successors is straightforward; these are templates for equivalent calls for all three event attachment methods:

$(selector).live(events, data, handler); // jQuery 1.3+

$(document).delegate(selector, events, data, handler); // jQuery 1.4.3+

$(document).on(events, selector, data, handler); // jQuery 1.7+

Another way would be to add right after you add it to the dom

$("#korpusChoose").html(korpusChooseTable);

then right after

$("#korpusChoose #TableKorpusGaleria tbody td").click(function(){
     alert();
});

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

Solution 2:

Because the table is created dynamically, you will need to use event delegation, using jquery's on. This will allow you to attach a handler before the element exists.

$("#korpusChoose #TableKorpusGaleria tbody td").click(function(e){

would instead be

$("container").on("focus", "#korpusChoose #TableKorpusGaleria tbody td",function(e){

where container is a selector for some static ancestor element which is not dynamically loaded. If no such container exists, document can be used, though this is to be avoided where possible.

Solution 3:

Because the table is generated dynamically you could use:

$('#mytable').live('click', function() {
    // Click event handler action here...
});

Using the live() method to bind event handlers they will also be triggered on elements created dynamically by AJAX calls or similar.

Update: Since .live() is deprecated since JQuery 1.7, thanks to Andrew, consider using .on() for event delegation.

Solution 4:

Use jquery $("table").live("click",function(){ }); Attach an event handler for all elements which match the current selector, now and in the future. Jquery click only binds the click event for present elements in the document .

http://jsfiddle.net/wFcpP/3/

Post a Comment for "Can't Click On The Table Created With Jquery"