1

I am trying to add a click event on some dynamically loaded content and I have this:

        $("#dailyCount table thead th").each(function(){
        var yd = "#" + $(this).attr("id");
        $(document).on("click", yd, function(){
            alert("a");
        });

    });

The element id is from 1 to the last day of current month. Any ideas ?

James Donnelly
  • 126,410
  • 34
  • 208
  • 218
ardb
  • 6,075
  • 5
  • 14
  • 16

4 Answers4

1

Instead of add a delegated handler for each element you can use one delegation to all elements returned from your selector.

So try:

$(document).on("click", "#dailyCount table thead th", function(){
    alert("a");
});

Demo: http://jsfiddle.net/agLBm/

Irvin Dominin
  • 30,819
  • 9
  • 77
  • 111
  • Doesn't work :(. Each th has different id from 1 to 30. – ardb Mar 19 '14 at 10:53
  • Have you tried it? Your selector will point all your th, the id is not relevant, check out the demo: http://jsfiddle.net/agLBm/ – Irvin Dominin Mar 19 '14 at 10:55
  • I think I'm doing it wrong somehow. Thanks anyway, I will figure this out later! – ardb Mar 19 '14 at 11:11
  • I tryed to put a class on elements and add events like this : $(document).on("click", ".dailyCountDel", function(){ alert("a"); }); , but it still doesnt work and I dont get any errors.. – ardb Mar 19 '14 at 11:32
  • It was a bug of Chrome, I've restarted it and worked. Thanks! – ardb Mar 21 '14 at 07:19
0

Trying to delegate an event using an id you retrieve dynamically is thr same as trying to attach the event to the dynamic element itself.

Therefore, either put ur code in a document.ready function or hardcode the id of the dynamic elements.

Banana
  • 7,424
  • 3
  • 22
  • 43
0

Just try this:

$(document).on("click", "#dailyCount table thead th", function(){
    alert("a");
});

Although, if i were you, i'd be getting away from DOM with selectors. Just add some class to TH elements in your table and select 'em.

<div id="dailyCount">
    <table>
        <thead>
            <th class="dailyCount-table-headCell">Whatever</th>
        </thead>
    </table>
</div>

$(document).on("click", ".dailyCount-table-headCell", function () {
    console.log("a");
});

It will allow you to change your markup without changing JS. As if you will need to do grid instead of table.

Vladislav Qulin
  • 1,872
  • 1
  • 17
  • 20
0

Assuming that you'll be using the id further in the code, try this:

$("#dailyCount table thead th").on("click", function(){
 var id = $(this).attr('id'); // id will now have the id of clicked element.
 alert("a");
});

Hope this helps.

Rishabh Shah
  • 679
  • 7
  • 20