Reputation: 8197
I have a table with one row in my HTML file. Now in jQuery I append lot of rows based on the data in the database. But the anchor tag which is created dynamically doesn't respond to events. How do I make this anchor tag respond to events?
jQuery part
//Appending rows from the Database
$('<tr> <td> </td> <td id="log'+i+'"><a href="viewlog.php" target="_blank">log</a></td></tr> ').appendTo('#container');
Event part in jQuery Now when I write a line of code like this it does not respond.
$('#container a ').click(function()
{
alert("Coming here ");
});
//HTML
<html>
<table id="container">
<tr>
<td>
Name
</td>
<td>
Link
</td>
</tr>
</table>
</html>
Upvotes: 0
Views: 1126
Reputation: 6696
As mck89 suggests, the event will not be bound if you run the code before appending the new dom.
You can chain the binding of events or use the live function instead.
$('your html')
.appendTo('#container')
.find('a')
.click(function() {
alert('You clicked!');
});
Upvotes: 2
Reputation: 19231
If you assign the click event at the beginning the elements created after won't get it.Try with:
$("#container a").live("click", function(){
...
});
in this way every time a link is created the event is attached to it (http://docs.jquery.com/Events/live#typefn).
Upvotes: 4