[英]Passing parameters to javascript button click handler
我在MVC4中有一个小应用程序。 它有一个网格,每一行都有两件事。 1)ID 2)按钮
当用户单击按钮时,我需要调用传递ID作为参数的javascript函数。 我如何在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
,则可以按照以下答案进行操作,只需捕获table
td
的'Id'
)
$('.btnView').click(function () {
var id = $(this).closest('tr').find('td').eq(0).text();
alert(id);
});
从按钮中删除onclick
处理程序(您没有名为myfunction
的函数)
由于您已经在上一列中获得了ID
值,因此可以使用
$('.btnView').click(function () {
var id = $(this).closest('tr').children('td').eq(0).text();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.