我在 Visual Studio 2017 Community(版本 15.9.6)中创建了一个简单的 ASP .Net Core(版本 2.2)Web 应用程序(非 MVC)
默认情况下,jQuery(版本 3.3.1)包含在 wwwroot/lib/jquery 目录中。
我正在获取 jQuery IntelliSense。
默认/Pages/Shared_Layout.cshtml 文件中正确引用了 jQuery。
我将以下代码添加到default.csthml页面:
<script type="text/javascript">
$(document).ready(function () {
$("p").click(function () {
$(this).hide();
});
});
</script>
<p>If you click on me, I will disappear.</p>
<p>Click me away!</p>
<p>Click me too!</p>
这个简单的代码默认情况下不起作用。
我不明白为什么。
控制台错误
0x800a1391 - JavaScript runtime error: '$' is undefined
Markup
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>@ViewData["Title"] - jQueryTest2</title>
<link rel="stylesheet" href="~/css/site.css" />
</head>
<body>
<header></header>
<div class="container">
<main role="main"> @RenderBody() </main>
</div>
<footer></footer>
<environment exclude="Development">
<script src="cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/>
</environment>
</body>
</html>
最佳答案
首先在 Layout.cshtml
页面的 body
底部添加 @RenderSection("Scripts", required: false)
。
然后您的脚本位于 @section Scripts
中,如下所示:
@section Scripts{
<script type="text/javascript">
$(document).ready(function () {
$("p").click(function () {
$(this).hide();
});
});
</script>
}
希望这能解决您的问题!
关于jQuery 在 ASP.NET Core 2.2 Razor View 中不可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54394478/