如何解决使用jQuery click处理程序
我的Razor视图中有下表,该表使用foreach浏览了ViewBag项。如您所见,每个按钮都有其值value="@item.Id"
。假设我的ViewBag中有十个项目,并且 id 从1到10开始。
<table class="table">
<thead>
<tr>
<th class="th-sm">Name</th>
<th class="th-sm">Operation</th>
</tr>
</thead>
@foreach (var item in ViewBag.Guests)
{
<tr>
<td>@item.LastName,@item.FirstName</td>
<td>
<button id="btn" value="@item.Id" class="btn btn-info btn-lg">Click Now</button>
</td>
</tr>
}
</table>
我还有一个点击处理程序:
<script>
$(document).ready(function ()
{
$('#btn').click(function () {
alert($(this).val());
});
});
</script>
执行代码后,将显示一个包含10条记录的表以及一个按钮。我想在单击按钮时在浏览器上显示带有用户ID的警报。但是,问题在于,它仅在警报上显示第一个按钮的值,而从第二个按钮到末尾均不显示任何内容。
有人知道我该如何解决这个问题?
解决方法
css“ id”和“ class”,“#”和“。”追溯
id必须是唯一的,类可以共享。 当您要定位多个按钮时,可以使用CSS类进行此操作。
请参见下面的小改动。
<table class="table">
<thead>
<tr>
<th class="th-sm">Name</th>
<th class="th-sm">Operation</th>
</tr>
</thead>
@foreach (var item in ViewBag.Guests)
{
<tr>
<td>@item.LastName,@item.FirstName</td>
<td>
<button class="btn btn-info btn-lg" id="btn-@item.Id"
value="@item.Id">Click Now</button>
</td>
</tr>
}
</table>
<script>
$(document).ready(function ()
{
$('.btn').click(function () {
alert($(this).val());
});
});
</script>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。