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

时间:2013-07-29 18:45:54

标签: javascript jquery html

我有以下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...
});

2 个答案:

答案 0 :(得分:3)

以下是您的工作方式:

$(".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]所在的元素。

href标记中的hre,而不是<a/>

答案 1 :(得分:2)

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

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