Reputation: 1724
I had write a simple code to delete a record on a table,
<td><a href = "#" class = "delete">Delete</a></td>
$('.delete').on('click', function() {
console.log('try');
});
The problem is that, If how many td's on the document I mean if there are 10 td's
with delete class, it logs the try
strign 10 times also.
Am I using on click
event listener wrong or this is an issue on the jquery. Thank you.
Upvotes: 0
Views: 1995
Reputation: 339786
A single call to .on()
will only ever result in a single event handler being launched.
IMHO, the most likely explanation for your fault is that you are actually calling .on()
multiple times - perhaps inside the loop that's creating the <td>
elements?
Within the single handler you can use DOM traversal to identify which column or element was clicked, and act accordingly. If, for example, you wanted to delete the current row you could use this:
for (...) {
// populate the table here
}
// handler will remove the row containing the clicked ".delete" link
$('.delete').on('click', function() {
$(this).closest('tr').remove();
});
EDIT based on new information from the OP, the problem is actually duplicate re-registration of the same handler over and over, each time a row is added.
In this case, the best solution is event delegation, where you put the handler on the table (just once), rather than on the individual elements:
$('#mytable').on('click', '.delete', function() {
// do your delete stuff here
});
Note the additional .delete
parameter to .on
- this tells jQuery which particular elements within the table you're interested in - the clicked element will be passed as this
.
You can make this call before the table is even populated, and it'll work on any .delete
element found inside the table, even ones added later, dynamically.
Upvotes: 3