gpt4 book ai didi

javascript - 如何设置 ID 并在 mvc 4 razor 中动态使用它?

转载 作者:数据小太阳 更新时间:2023-10-29 03:49:24 25 4
gpt4 key购买 nike

我在 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>
}

但是,现在我需要 eash 的 .click() 函数 <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/

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