Reputation: 85
I have a script that dynamically generates a grid by using a table.
//createGrid(height, width);
createGrid(1, 2);
//one row with 2 cols
Which creates this:
<table>
<tr>
<td></td>
<td></td>
</tr>
</table>
I need an onclick event for the td tags that add/changes their class. I've tried a few solutions to no avail. Any ideas? I'm not great at Jquery.
Upvotes: 0
Views: 2249
Reputation: 148140
You can use on jquery function for binding the dynamically generated item for event delegation, It binds the existing elements with event and It will also bind element which are added dynamically. $('td').click(function(){});
will only bind the existing element but not the added dynamically after he binding.
$(document).on("click", "td", function(){
alert("clicked");
});
Delegated events
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers, reference.
You can change document with some parent element selector.
Upvotes: 0
Reputation: 142
Another alternative using find
, live
and toggleClass
$("table").find("td").live("click", function() {
$(this).toggleClass("selected");
});
Upvotes: 0