简体   繁体   中英

How to get the table cell of a row that was clicked with JQuery

I have a table in HTML, and I have an onclick event for its rows.

I was wondering if it was possible to find out which cell of the row was clicked, without having a seperate handler for each cell?

I have a table:

<tr class="new_row">
   <td class="date">date</td>
   <td class="name">name</td>
   <td class="delete">delete</td>
</tr>

and jquery:

$(".new_row").click(function(){
   if(delete was clicked){
       delete the row
   }
});

That is what I want to do basically, detect if the delete cell was clicked.

Is this possible?

Firstly you should not define more than one element with same id, it will cause trouble, you can replace id='delete' with class='delete' .

// on click td with class delete:
$("td.delete").click(function(){
   //delete was clicked so remove tr
   $(this).parent().remove();
});

You can do it like this

Live Demo

$(".new_row").click(function(event){       
    if($(event.target).text() == 'delete')
    {       
      $(this).remove();      
    }
});

Look at the id of the event.target . If it matches delete , then you can process a delete.

However, since this in a table, I'm guessing that you have multiple rows. If this is the case, does that mean that you have multiple cells with the same ID? If so, this isn't valid HTML and it could cause problems with your jQuery code, when you try to use CSS selectors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM