我有一个C#,MVC网站,我希望将网站所需的所有JavaScript / jQuery都包含在一个文件中,但是某些JavaScript / jQuery仅在某些页面上需要。

示例,当前在JavaScript文件中,我具有类似以下的代码-

$(document).ready(function () {

    $('#myId').click(function () {
        doCoolStuff();
    });

});


上面的语句在每一页上执行,但只在一页上需要。使JavaScript / jQuery仅在需要它的页面上运行的最佳方法是什么?

最佳答案

您可以使用Section在必要时包括项目,并使其不需要(但在存在时包括在内)。

_Layout.cshtml

@* ... *@
@RenderSection("Scripts", required: false)
@* ... *@


SomeView.cshtml

@* ... *@
@section Scripts
{
    @* direct inclusion *@
    <script>
        $(function(){
            // your code here
        });
    </script>

    @* or file reference *@
    <script src="@Url.Content("~/Content/alternate.script.js")"></script>
}
@* ... *@

关于c# - 仅某些页面需要JavaScript和jQuery,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19142925/

10-14 15:21
查看更多