在我的 MVC 索引页面中,对于 View 模型中的每个元素,它通过局部 View 呈现。
然后我需要在这些局部 View 中的每一个上运行一个小脚本,并尝试使用 jQuery.Each()
但是,我似乎无法让它迭代为 $ get
始终返回 1,而不是 $get
中的实际元素数。
Index.cshtml
@model IEnumerable<ViewModels.DummyVM>
@{
ViewBag.Title = "index";
}
<h2>index</h2>
<div>
@for (int i = 1; i <= 10; i++)
{
@Html.Partial("pv", i);
}
</div>
@section Scripts
{
<script type="text/javascript">
$(function () {
alert($("#LogEntry").length);
})
</script>
}
PV.cshtml
@model int
<div id="LogEntry">
Log Entry : @(Model)
</div>
对于上面的简化测试,一旦页面有 .ready() 然后遍历 并转储到控制台,但我只得到 Log Entry : 0
最佳答案
id
在同一个文档中应该是唯一的,而不是使用类:
@model int
<div class="LogEntry">
Log Entry : @(Model)
</div>
然后在你的 JS 代码中使用类选择器 .
:
$(function () {
alert($(".LogEntry").length);
})
如果您无法编辑您的 PV.cshtml
页面,您可以使用:
$(function () {
alert($("[id='LogEntry']").length);
})
希望这对您有所帮助。
关于javascript - 部分 View 中 div 上的 jQuery.each 总是返回 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37110460/