javascript 如何在 mvc 4 razor 中设置 ID 并动态使用它?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14406203/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How set ID and use it dynamically in mvc 4 razor?
提问by Jeyhun Rahimov
I have html elements in foreach
. I cannot declare ID name to those manually.
I used id='ProductSelect_@(item.Id)'
to set Id:
我在 .html 中有 html 元素foreach
。我无法手动向那些声明 ID 名称。我曾经 id='ProductSelect_@(item.Id)'
设置Id:
foreach (var item in Model)
{
<a href="#" id='ProductSelect_@(item.Id)' class="select-link">Select this</a>
}
But, now I need .click()function for eash <a>
link to do my some operations. How write click function for dynamic ID's?
I checked this, but it does not work :
但是,现在我需要eash链接的.click()函数<a>
来执行我的一些操作。如何为动态 ID 编写点击功能?
我检查了这个,但它不起作用:
$("#ProductSelect_@(item.Id)").click(function () {
//any operation
});
Edit:
编辑:
<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>
This click() functions send request to controller iteration counts times. What is wrong in my code?
此 click() 函数将请求发送到控制器迭代计数次数。我的代码有什么问题?
回答by Eli Gassert
I would suggest using attributes.
我建议使用属性。
foreach (var item in Model)
{
<a href="#" data-id='@item.Id' id='ProductSelect_@(item.Id)' class="select-link">Select this</a>
}
then in JS...
然后在JS...
$('.select-link').click(function()
{
var id = $(this).attr('data-id');
});
That way you're wired to all similar links (e.g. select-list
) without a separate handler function for each #id.
这样您就可以连接到所有类似的链接(例如select-list
),而无需为每个 #id 设置单独的处理函数。