Dynamically added DOM element don’t get click event bounds to them as they have to exist before the event is created, you need to use jQuery’s event delegation in order to target elements that exist after the DOM has loaded.
Also your event would never have worked as your class is trbank, your searching for a parent TD element yet your above code shows no TD apart from the children inside the TR elements.
$(function() {
$(document).on('click', '.trbank .mybtn', function() {
alert('You clicked the button for row: ' + $(this).parents('tr').index());
});
});
What you need to do is to attach the handler to an element that is present when the DOM is loaded (e.g. document), then specify a selector (e.g. “.mybtn”) with which to filter the descendants of the selected elements which trigger the event.
Hi @pullo and @chris.upjohn, Thank you so much your solution is working…:)…@pullo, thank you for explaining me
What you need to do is to attach the handler to an element that is present when the DOM is loaded (e.g. document), then specify a selector (e.g. “.mybtn”) with which to filter the descendants of the selected elements which trigger the event.
…this helps me a lot.
One more thing i couldn’t understand what is the difference between the .parent and .parents,when to use this .parent or .parents when traversing the DOM ?
.parent() gets the parent of each element in the current set of matched elements. .parents() gets the ancestors of each element in the current set of matched elements.
Both results sets can optionally be filtered by a selector.
The biggest difference between the two methods is that .parent() only travels a single level up the DOM tree.
You can run this example on your PC to see what I mean:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>parent vs parents</title>
</head>
<body>
<div>
<ul>
<li>
<ul>
<li>
<a href="#" id="myLink">My link</a>
</li>
</ul>
</li>
</ul>
</div>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>
console.log("My link's direct parent is a " + $("#myLink").parent().prop("tagName") + " element");
console.log("All of my link's parents are: " + $("#myLink").parents().map(function() { return this.tagName; }).get().join(", "));
</script>
</body>
</html>