javascript - 部分 View 中 div 上的 jQuery.each 总是返回 1

标签 javascript jquery html css asp.net-mvc

在我的 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/

相关文章:

javascript - AngularJS 仅在解析时返回两个 http get 请求

javascript - node.nextSibling 和 ChildNode.nextElementSibling 有什么区别?

javascript - 将 THREE.ParametricGeometry 调整为边界框尺寸

jquery - 时间选择器自动打开

php - 显示最后插入或最后更新的行

html - 内部 div 未包含在 100% 宽度的父 div 中

javascript - javascript 中日期抛出错误

ios - 停止 jQuery Mobile 滑动事件双冒泡

javascript - 图片对象设置src前是否需要先设置onload函数?

javascript - 如何下载客户端内容