获取从 MVC 表中单击的行的 ID

Rah*_*wal 3 javascript asp.net-mvc jquery

我想Id在用户单击按钮时单击行。

我的代码如下。

   <table cellpadding="0" cellspacing="0" id="ProductGrid">
    <tr>
        <th>P Id</th>
        <th>P Name</th>
        <th>Price</th>
        <th></th>
    </tr>
    @foreach(Mvc4API.linqtosql.tblProduct prod in Model)
    {
        <tr>
            <td>@prod.Pid</td>
            <td>@prod.Pname</td>
            <td>@prod.Price</td>
            <td><button type="button" class="ids" id="btnpartial" value="showdetail" onclick="getview()"></button></td>
        </tr>
    }
</table>
Run Code Online (Sandbox Code Playgroud)

我试过:-

function getview() {
    debugger;
    var productId = $("#ProductGrid .ids").closest("tr").find("td").eq(0).html();
});
Run Code Online (Sandbox Code Playgroud)

但它不起作用。

小智 5

重复的 id 属性是无效的 html。删除id属性onclick和使用

$('.ids').click(function() {
    var productId = $(this).closest("tr").find("td").eq(0).text();
});
Run Code Online (Sandbox Code Playgroud)

或者,在data属性中添加值

<button type="button" class="ids" data-id="@prod.Pid"></button>
Run Code Online (Sandbox Code Playgroud)

并使用

$('.ids').click(function() {
    var productId = $(this).data('id');
});
Run Code Online (Sandbox Code Playgroud)

请注意,您当前的选择器 -$("#ProductGrid .ids")返回所有按钮元素,而不是您单击的元素。