Say I have a table:
<table id="myTable">
<tbody>
<tr>
<td>
<a class="removeLink" >Remove</a>
</td>
</tr>
<tr>
<td>
<a class="removeLink" >Remove</a>
</td>
</tr>
</tbody>
</table>
<a id="addLink">Add</a>
So the aim of the game here is that when a remove link is clicked the associated row will dissapear.
So I have some javascript:
<script type="text/javascript">
$(document).ready(function () {
$('.removeLink').click(function () {
$(this).closest('tr').hide('slow');
});
$('#addLink').click(function () {
$('#myTable').append('<tr><td><a class="removeLink" >Remove</a></td></tr>');
});
});
</script>
So I have the dissappearing part working with this.
However the add link adds a row to the table.
Now when I click the remove on a row that has been added it doesn’t dissapear. Makes sense as it hasn’t had its click
event set up.
How to code this so that links that are added will have their removeLinks hooked up to hide?
Also is this a strange way to even add the row? Is there a better way?
You can use
on():on()essentially binds the named event(s) to the specified element (#myTable), and, on ‘hearing’ that, or those, event(s) inspects the target to see if it matches the supplied selector (the second of the parameters passed to theon()method. If it does, the anonymous, third parameter, function is executed.It seems better to bind the event-handling to the element closest to the elements affected by the event that exists in the DOM at the point of event-handling/binding. In this case that would be the
tbody, which would result in the following (only-slightly) modified code:Other alternatives are
delegate()(though this has been superseded byon()from jQuery 1.7):Or
live(), though this is deprecated as of jQuery 1.7, and, even wherelive()is available,delegate()is recommended in preference. That said:References:
delegate().live().on().