jQuery从列中的隐藏输入中获取值

jQuery get value from hidden input in column

本文关键字:输入 获取 隐藏 jQuery      更新时间:2023-09-26

我得到了以下HTML表。。。

<table>
  <thead>
    <tr>
      <th>Nr.</th>
      <th>Name</th>
      <th>Info</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td>Laura</td>
      <td><input type="hidden" value="1"><a href="#" class="info">Info</a></td>
    </tr>
    <tr>
      <td>2</td>
      <td>Sabrina</td>
      <td><input type="hidden" value="2"><a href="#" class="info">Info</a></td>
    </tr>
  </tbody>
</table>

单击链接时,如何使用jQuery获取隐藏输入字段的值?

$(".info").click(function() {
  // Here I need to find out the value...
});

以下是您的操作方法:

$(".info").click(function(e) {
  //just in case, will be useful if your href is anything other than #
  e.preventDefault();
  alert($(this).prev('input[type="hidden"]').val());
});

prev方法将搜索上一个元素,即input[hidden]所在的位置。

以及<a/>标签中的href,而不是hre

您也可以使用属性<a href="#" data-hidden="1" class="info">不需要使用隐藏字段

$(".info").click(function(e) {
  e.preventDefault();
  alert($(this).data('hidden')); // or $(this).attr('data-hidden');
});