您好,通过阅读本网站上的建议,我了解到脚本应位于 _layout 页面的底部。我的问题是我不确定“底部”到底在哪里。有些人说它就在标签之前,但这对我不起作用。我尝试过将脚本放在很多地方,但似乎没有地方起作用。有人可以告诉我我做错了什么吗?
这是我的关于页面
@{
ViewBag.Title = "About Us";
}
<h2>About</h2>
<p>
Put content here.
</p>
<script type="text/javascript">
$(function () {
alert("Hello World");
});
</script>
这是我的_Layout 页面
<!DOCTYPE html>
<html>
<head>
<title>@ViewBag.Title</title>
<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
@* jQuery works if this line is here but not if it is at the bottom
<script src="@Url.Content("~/Scripts/jquery-1.6.2.min.js")" type="text/javascript"></script>
*@
</head>
<body>
<div class="page">
<div id="header">
<div id="title">
<h1>
My MVC Application</h1>
</div>
<div id="logindisplay">
@Html.Partial("_LogOnPartial")
</div>
<div id="menucontainer">
<ul id="menu">
<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("About", "About", "Home")</li>
</ul>
</div>
</div>
<div id="main">
@RenderBody()
</div>
<div id="footer">
</div>
</div>
@* jQery does not work if the script is here! *@
<script src="@Url.Content("~/Scripts/jquery-1.6.2.min.js")" type="text/javascript"></script>
</body>
</html>
一些替代方案
绝对有可能将 jquery 放在 body 标记的末尾。理想情况下,你脑子里唯一的 js 是modernizr
, html5shiv
或类似的。
Option 1
Put a @RenderSection("scripts", required: false)
jQuery 之后<script...
元素作为 body 元素内的最后一行。然后在您的任何视图中您都会使用
@section scripts
{
<script type="text/javascript">
$(function () {
// page specific js code here
});
</script>
}
Option 2
在你的 jQuery 之间script
元素和你的结束body
元素有一个script
指向相关操作/视图的相关 js 文件的元素:
<script
src="@Url.Content("~/Scripts/" + ViewContext.RouteData.GetRequiredString("action") + ".js")"
type="text/javascript">
</script>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)