使用 Jquery 在 Razor 中获取元素值

Get element value in Razor with Jquery

我有一个类似 that.I 的 foreach 循环,希望在按下“删除”按钮时获取项目 ID。

 <table class="table">
        <thead>
            <tr>
                <th>#</th>
                <th>Name - Sirname</th>
                <th>Date - Time</th>
                <th>Message</th>
                <th>id</th>
            </tr>
        </thead>
        <tbody>

            @foreach (var item in Model.Items)
            {
                <tr>
                    <th>@(Model.Items.IndexOf(item)+1)</th>
                    <td>@item.Name</td>
                    <td>@item.DateTime</td>
                    <td>@item.Message</td>
                    <td  id="itemId">@item.id</td>
                    <td><button class="btn btn-danger">Delete</button></td>
                </tr>
            }

        </tbody>
    </table>

我的Qjuery就是这样;

        $("button").click(function () {
            var id = $("#itemId").html();
            $("#sonuc").html(id);
        });
    });

我的结果一定在里面;

<p id="sonuc"> </p>

但每次它只显示第一个项目的 id table。那么如何使用 Jquery 获取循环中每个元素的值?

您可以使用var id = $(this).parent().prev().text();

演示

$("button").click(function() {
  var id = $(this).parent().prev().text();
  $("#sonuc").html(id);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table">
  <thead>
    <tr>
      <th>#</th>
      <th>Name - Sirname</th>
      <th>Date - Time</th>
      <th>Message</th>
      <th>id</th>
    </tr>
  </thead>
  <tbody>

    <tr>
      <th>@(Model.Items.IndexOf(item)+1)</th>
      <td>@item.Name</td>
      <td>@item.DateTime</td>
      <td>@item.Message</td>
      <td>@item.id1</td>
      <td><button class="btn btn-danger">Delete</button></td>
    </tr>

    <tr>
      <th>@(Model.Items.IndexOf(item)+1)</th>
      <td>@item.Name</td>
      <td>@item.DateTime</td>
      <td>@item.Message</td>
      <td>@item.id2</td>
      <td><button class="btn btn-danger">Delete</button></td>
    </tr>

  </tbody>
</table>
<p id="sonuc"> </p>

每个元素的 ID 必须是唯一的,如果您想获取项目 ID 的值并在按下删除按钮后使用剃须刀,您可以将删除按钮上的项目 ID 值设置为 ID 或数据属性,这样 你可以试试

<td id="itemId_@item.id">@item.id</td>

<button id="@item.Id" class="btn btn-danger">Delete</button>

而不是

<td id="itemId">@item.id</td>

<button class="btn btn-danger">Delete</button>

  $("button").click(function () {
        var id = this.id; // value of itemId
        
    });
});