我在foreach
中有html元素。我无法手动向那些人声明ID名称。
我使用id='ProductSelect_@(item.Id)'
设置ID:
foreach (var item in Model)
{
<a href="#" id='ProductSelect_@(item.Id)' class="select-link">Select this</a>
}
但是,现在我需要 .click()函数来实现asht
<a>
链接,以执行一些操作。如何为动态ID编写点击功能?我检查了一下,但是不起作用:
$("#ProductSelect_@(item.Id)").click(function () {
//any operation
});
编辑:
<script>
$(document).ready(function () {
$('.select-link').click(function() {
var id = $(this).attr('data-id');
url = '@Url.Action("SelectThis", "Product")';
var data = { id: '@Model.Id' };
$.post(url, data, function (result) {
if (result.success) {
alert("Thanks");
}
else {
alert("Problem occured...");
}
});
});
});
</script>
这个click()函数将请求发送到 Controller 的迭代计数次数。我的代码有什么问题?
最佳答案
我建议使用属性。
foreach (var item in Model)
{
<a href="#" data-id='@item.Id' id='ProductSelect_@(item.Id)' class="select-link">Select this</a>
}
然后在JS中...
$('.select-link').click(function()
{
var id = $(this).attr('data-id');
});
这样,您就可以连接到所有类似的链接(例如
select-list
),而无需为每个#id使用单独的处理函数。关于javascript - 如何设置ID并在MVC 4 Razor 中动态使用它?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14406203/