jquery - 获取与按钮同一行的第一个 td 元素的值

标签 jquery

所以我有一个如下结构的表格:

<table>
    <thead>
        <tr>
            <th>Id</th>
            <th>Name</th>
            <th>Company</th>
            <th>Position</th>
            <th>Start Date</th>
            <th>Role</th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        <tr>
             <td><?php info displayed with php ?></td>
             <td><?php info displayed with php ?></td>
             <td><?php info displayed with php ?></td>
             <td><?php info displayed with php ?></td>
             <td><?php info displayed with php ?></td>
             <td><?php info displayed with php ?></td>
             <td><a href="#" class="usr-edit">Edit</a></td>
         </tr>
     </tbody>
</table>

我想要做的是当用户单击编辑时从第一列获取 Id 的值。如果你想 mock 我失败的尝试,这里是:

$('.usr-edit').click(function() {
    var a = $(this).prev().prev().prev().prev().prev().prev().text();

    alert(a);
});

最佳答案

$('.usr-edit').click(function() {
  var a = $(this).closest('tr').find('td:nth-child(1)').text();

  console.log(a);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <th>Id</th>
      <th>Name</th>
      <th>Company</th>
      <th>Position</th>
      <th>Start Date</th>
      <th>Role</th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
      <td><a href="#" class="usr-edit">Edit</a>
      </td>
    </tr>
  </tbody>
</table>

试试这个

关于jquery - 获取与按钮同一行的第一个 td 元素的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35459395/

相关文章:

javascript - 当我点击排行榜中的名字时显示详细信息(可能在弹出窗口中)

asp.net - 可以从 jQuery 触发 asp.net 验证吗?

jquery - 如何使用 Jquery 将 url 获取到 div 中

android - jPlayer持续时间和进度错误

javascript - 如何解析每个周期有两个低潮/高潮的 worldtide.info JSON?

jquery - 在 jQuery 中旋转 Div 元素

javascript - 单击时在 div 中显示图像不起作用

javascript - 给定一个预定义的变量,我如何在 jQuery 中计数到一定数量

Jquery 加载脚本标签

javascript - 如何使用 jquery-ui 将缓动与滚动顶部一起使用?