获取与按钮在同一行中的第一个td元素的值

时间:2016-02-17 14:27:01

标签: jquery

所以我有一个像这样的结构表:

classdef MobileBaseStation
    properties(GetAccess=private, SetAccess=private)
        DataChannel = struct('TxScheme','SpatialMux','NLayers',4);
    end

    ...

    properties(Dependent=true)
        TxScheme;
        NLayers;
    end

    methods
        function v = get.TxScheme(this), v = this.DataChannel.TxScheme; end
        function v = get.NLayers(this), v = this.DataChannel.NLayers; end

        function this = set.TxScheme(this,v)
            assert(ismember(v,this.supportedTxSchemes),'Invalid TxScheme - %s.',v);
            this.DataChannel.TxScheme = v;
        end

        ...
    end
end

我想要做的是在用户点击编辑时从第一列获取Id的值。如果你想嘲笑我失败的尝试,那就是:

<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>

4 个答案:

答案 0 :(得分:4)

$('.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>

试试这个

答案 1 :(得分:0)

你可以在表元素中使用dom引用来获取你想要的单元格

var td = this;
var tr = this.parentNode;
var firstTd = tr.cells[0];

答案 2 :(得分:0)

简单!

$('.usr-edit').click(function() {
    var a = $(this).parent().find('td:first-child').text();
    console.log(a);
});

编辑:要找到tr父母,您就可以这样做。

$('.usr-edit').click(function() {
    var a = $(this).parents('tr').find('td:first-child').text();
    console.log(a);
});

肮脏的方式

$('.usr-edit').click(function() {
    var a = $(this).parent().parent().find('td:first-child').text();
    console.log(a);
});

答案 3 :(得分:0)

您可以在<tr> <tr class="yourClass">上添加课程,并使用:

$('.yourClass').find('td:first-child').text();