gpt4 book ai didi

c# - 动态生成 jQuery 函数 mvc 4 razor

转载 作者:行者123 更新时间:2023-11-30 17:57:44 26 4
gpt4 key购买 nike

目前,我正在将对象列表从 Controller 传递到 View ,并根据对象的名称生成标签。

我想做的是生成一个 jQuery 函数,该函数将在每个标签被单击后动态创建函数(切换具有相对标签 ID 的表单)。

jQuery函数不工作,我无法在网页中输出正确的jQuery函数......你能给我一些提示吗?

<table>
@foreach (var item in Model)
{
<tr>
<td>
@Html.Label(item.productName, new { @id = item.productId})
</td>
</tr>
}
</table>


<script type="text/javascript">
$(document).ready(function () {
@foreach (var item in Model)
{
$(@item.productId).click)(function({
//do something
}));
}

});
</script>

非常感谢!

最佳答案

对于初学者来说,你的 JS 语法是错误的。你想要做的是给所有这些标签一个类名(比如 product_lbl)或者一个数据属性(如果你不喜欢语义类名)比​​如 product-lbl。这样您就不必执行第二个循环来添加点击事件处理程序。你只需要一个,就像这样:

$('.product_lbl').on(
'click',
function() { /* Do something for whichever label was clicked */ }
);

$('[product-lbl]').on(
'click',
function() { /* Do something for whichever label was clicked */ }
);

关于c# - 动态生成 jQuery 函数 mvc 4 razor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17778863/

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