1

How to delete a specific row of a table using jQuery?

I have a table like the following:

HTML

<table id="data-filter">
  <tr>
     <td>1</td>
     <td>Harry Potter</td>
     <td><span class="delete"></span></td>
   </tr>
   <tr>
     <td>2</td>
     <td>Frodo Baggins</td>
     <td><span class="delete"></span></td>
   </tr>
</table>

If the user presses "x" on any line, that particular line will be deleted. I can find which line is pressed, but I cannot determine exactly which lines of "x" will be pressed. The following is jQuery and CSS code:

JQuery

$(document).on('click', '#data-filter tr', function() {
    rn = this.rowIndex;
    alert('You clicked row: '+rn); // do something to remove this row
});

CSS

.delete:after { content:"x";}

I want to trigger the delete event only when the user clicks on a specific line of "x", and not on the entire line or only on any part of the line. I think I just don’t have the right selector for this, but I'm not sure.

+3
source share
2 answers

You can use thisto refer to the element intended by the handler, therefore

$(document).on('click', '#data-filter tr .delete', function() {
    $(this).closest('tr').remove()
});

, , , "", delete, .closest(), tr, , . remove(),

+1

, :

$(document).on('click', '#data-filter tr .delete', function() {
            this.parentElement.parentElement.remove();
        });

hashtag ( " " ), jQuery, HTML

, , TR

, .

+1

All Articles