简体   繁体   English

单击表行时如何从单元格获取值

[英]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 . 我正在尝试使用class editlink从单元格获取href值。 This is what I have tried but I'm getting undefined in the alert . 这是我尝试过的方法,但在alert变得undefined

<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. 首先请注意, delegate()已被弃用。 Instead, use the delegated signature of the on() method. 而是使用on()方法的委托签名。 This may also mean that you need to upgrade the version of jQuery you're using. 这也可能意味着您需要升级正在使用的jQuery版本。

As for the issue you have, it's because .editlink is the td . 至于您遇到的问题,是因为.editlinktd The href property is on the a element, so the selector needs to be .editlink a . href属性位于a元素上,因此选择器必须为.editlink a Also, closest('tr') is redundant, as the event handler is already bound to the tr . 同样,由于事件处理程序已经绑定到trclosest('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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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