简体   繁体   中英

How to get the value from a cell when table row is clicked

I am trying to get the href value from the cell with the class editlink . This is what I have tried but I'm getting undefined in the alert .

<table id="table_1">
  <thead></thead>
  <tbody>
    <tr>
      <td>sometext</td>
      <td class="editlink"><a href="/linkid444">edit</a></td>
    </tr>
    <tr>
      <td>sometext2</td>
      <td class="editlink"><a href="/linkid555">edit</a></td>
    </tr>
  </tbody>
  <tfoot></tfoot>
</table>
$(document).ready(function() {
  $("#table_1").delegate("tr", "click", function() {
    var linkdata = $(this).closest('tr').find('.editlink').attr("href");
    alert(linkdata);
  });
});

Firstly note that delegate() has been deprecated. Instead, use the delegated signature of the on() method. This may also mean that you need to upgrade the version of jQuery you're using.

As for the issue you have, it's because .editlink is the td . The href property is on the a element, so the selector needs to be .editlink a . Also, closest('tr') is redundant, as the event handler is already bound to the tr . Try this:

 $(document).ready(function() { $("#table_1").on('click', "tr", function() { var linkdata = $(this).find('.editlink a').attr("href"); console.log(linkdata); }); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table id="table_1"> <thead></thead> <tbody> <tr> <td>sometext</td> <td class="editlink"><a href="/linkid444">edit</a></td> </tr> <tr> <td>sometext2</td> <td class="editlink"><a href="/linkid555">edit</a></td> </tr> </tbody> <tfoot></tfoot> </table> 

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