使用 javascript/jquery 从 table 的给定行中提取 Cell/Td/tabledata 值

Extract a Cell/Td/tabledata value from a given row of a table using javascript/jquery

这是我在 Asp.net MVC razor 视图

中使用的 html table
<table class="table-striped table-bordered">
  <thead>
    <tr>

        <th class="col-md-2">
            Id
        </th>
        <th class="col-md-4">
            Description
        </th>
        <th class="col-md-3">
            Quantity
        </th>
        <th class="col-md-3">
            AssetType
        </th>
    </tr>
</thead>
<tbody>
    @foreach (var i in Model)
    {
        <tr>
            <td class="col-md-2">
                @i.Id
            </td>
            <td class="col-md-4">
                @i.Description
            </td>
            <td class="col-md-3">
                @i.Count
            </td>
            <td class="col-md-3">
                @i.AssetType
            </td>
            <td>
              <a onclick="getId()">Edit</a>
            </td>
        </tr>
    }
</tbody>
</table>

我的JS代码

<script type="text/javascript">
    var getId = function () {
       //get current row 
       var currentRow = $(this).closest('tr');
       // get the id from the current row. or is there any better way ?         
    }   
</script>

你好在上面的代码中。我想要做的就是当用户选择 table 中给定行的编辑 link 时。我想提取所选行的 id 值。

任何人都可以在这方面指导我吗?我看过介绍如何从每一行中获取给定单元格值的文章,但没有找到解释如何从给定行中提取数据单元格值的文章。

你已经有了它,因为你正在从服务器端生成 HTML,当用户单击时将 id 传递给函数以用它做任何你想做的事情。

 <td>
    <a onclick="getId('@i.Id')">Edit</a>
 </td>

function getId(id) {...}

或者,如果您愿意,可以使用如下内容:

 <a onclick="getId(this)">Edit</a>
        function getId(dom){
          var id = $(dom).parent().find('.col-md-2').html();
         }

您可以在编辑 link 中将 id 值放入 data-id 属性,如下所示

<a data-id="@i.Id" class="edit-button" href="#">Edit</a>

将点击事件处理程序添加到编辑link,您可以使用$(this).data('id')

获取id值
<script type="text/javascript">
    $('.edit-button').on('click', function (e) {
        e.preventDefault();
        alert($(this).data('id'));
    });
</script>

工作fiddle:http://jsfiddle.net/ds4t6jur/