我正在使用 jqgrid 开发 ASPNET MVC 4 项目。
那里,ASPNET MVC 4默认放置
@Scripts.Render("~/bundles/jquery")
在它末尾的 _Layout.cshtml 文件中。
现在,我有一个使用 jqgrid 的 Index.cshtml
<script type="text/javascript">
jQuery("#ajaxGrid").jqGrid({
所以我必须包含像这样的 jqgrid 脚本
@section jqgridScripts
{
<script src="@Url.Content("~/Scripts/jqgrid/i18n/grid.locale-en.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jqgrid/js/jquery.jqGrid.min.js")" type="text/javascript"></script>
}
但在使用 .jqgrid 之前,我需要加载 jqgrid 脚本,而这又需要加载 jquery 脚本,因此,jquery 脚本需要位于 _Layout.cshtml 文件的顶部而不是末尾。
根据最佳实践,需要在文件末尾加载 jquery 脚本,但如果我这样做,在 Index.cshtml 文件中它不知道 jQuery 是什么。
我不能将 jqquery 脚本和下面的 jqgrid 脚本放在 _Layout.cshtml 文件的底部,因为上面是使用 jqgrid 脚本的 Index.cshtml 文件内容。
为了能够在最后放置 jQuery 并且仍然能够在 View 中使用带有 jquery 的东西,我是否遗漏了什么?
谢谢!吉列尔莫。
最佳答案
__Layout.cshtml:
@Scripts.Render("~/bundles/jquery")
@RenderSection("jqgridScripts", required: false);
@* for script in current page *@
@RenderSection("pageScripts", required: false);
索引.cshtml:
@section pageScripts
{
<script type="text/javascript">
jQuery("#ajaxGrid").jqGrid({
...
</script>
}
但最好的做法是为您的代码创建一个单独的 javascript 文件,如下所示:
__Layout.cshtml:
@Scripts.Render("~/bundles/jquery")
@RenderSection("pageScripts", required: false);
索引.cshtml:
@section pageScripts
{
<script src="@Url.Content("~/Scripts/jqgrid/i18n/grid.locale-en.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jqgrid/js/jquery.jqGrid.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/Site/myscript.js")" type="text/javascript"></script>
}
我的脚本.js:
$(function() {
jQuery("#ajaxGrid").jqGrid({ ... });
});
关于javascript - ASPNET MVC 4 应用程序中的 Jquery 脚本顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13585787/