Reputation: 3844
I've been working with jQuery to do a lot of event driven programming and I've been told that event handlers should be attached to the closest static parent container. However, when I try to attach the event listener to the table, it doesn't work. I only have it working by watching the entire document. Here's what I have that works:
$(document).on("click", "td", function() {
//do something
})
However, I want to get something more like this:
$("#tableID").on("click", "td", function() {
//do something
})
The second version doesn't work though. I don't think it ever detects any clicks on my table. Why would this be?
Upvotes: 0
Views: 221
Reputation: 119867
Because the selector should be a string. Put quotes around it and it should work.
$('#tableID').on('click', 'td', function() {
//do something
});
If the table is loaded via AJAX, then the delegate target (which would be the one in $()
) should be an element present on the page during the execution of this binding code. The usual target is document
because it's always there. But it's too far up the DOM tree, that's why you are allowed to choose your target.
Upvotes: 0
Reputation:
You need to run the code after the DOM is ready... or at least after that element is ready.
$(function() {
$("#tableID").on("click", "td", function() {
//do something
});
});
And of course you need to make sure the ID is correct, and unique.
Upvotes: 1