gpt4 book ai didi

javascript - 将参数传递给 javascript 按钮单击处理程序

转载 作者:行者123 更新时间:2023-11-28 15:36:04 24 4
gpt4 key购买 nike

我有一个 MVC4 中的小应用程序。它有一个网格,每行都有两个东西。1)身份证件2) 按钮

当用户单击按钮时,我需要调用一个 javascript 函数,传递 ID 作为参数。我怎样才能在 MVC 中做到这一点。以防万一,我可以轻松瘦身。请帮忙

下面是我的代码。

@model IEnumerable<Models.Asset>

@{
ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
Id
</th>

<th>
Show
</th>
</tr>

@foreach (var item in Model) {
<tr>
<td width="80">
@item.Id
</td>


<td>
<button class="btnView" onclick="myfunction(@item.someProperty)">Show</button>
///How can I pass @item.someProperty as an parameter to click handler?
</td>
</tr>
}
</table>


<div id="imageDisplay">

<p>

</p>
</div>

@section scripts{
<script type="text/javascript">
$(function () {
$('#imageDisplay').dialog({
autoOpen: false
});

$('.btnView').click(function () {
alert('ok');
//How can I get id as an parameter to this function?
});

});

</script>
}

最佳答案

首先删除onclick来自按钮的处理程序(当您使用 jquery 处理 click 事件时不需要它)

试试这个:

HTML:-

<td>
<button class="btnView" data-prop="@item.someProperty">Show</button>
</td>

JQUERY:-

$('.btnView').click(function () {
var prop = $(this).attr('data-prop');
alert(prop);
});

或者

 $('.btnView').click(function () {
var prop = $(this).data('prop');
alert(prop);
});

或者(如果您不想在按钮上添加 data-prop ,那么您可以按照下面的答案进行操作,只需捕获 'Id' ,它位于您的 tdtable 中)

$('.btnView').click(function () {
var id = $(this).closest('tr').find('td').eq(0).text();
alert(id);
});

关于javascript - 将参数传递给 javascript 按钮单击处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25616043/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com