jQuery 在 ASP.NET Core 2.2 Razor View 中不可用

标签 jquery asp.net-core

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

相关文章:

javascript - 用下拉列表替换文本框

jquery - 如何在 ruby​​ on rails 中发出 ajax 请求?

javascript - Jquery - 使用窗口滚动时抖动滚动

c# - 如何从另一个项目的appsettings文件读取连接字符串

asp.net-core - asp.net core 中的命名空间 'Web' 中不存在命名空间 'System' 的类型(是否缺少程序集引用)

jquery - 我可以将 tagit 与 twitter bootstrap 一起使用吗?

javascript - 了解 AMD : how to handle response flow with a one-way module relationship

c# - Entity Framework Core 5.0 警告限制运算符 ('Skip'/'Take' ) 没有 'OrderBy' 运算符

c# - 在 ASP.NET Core 应用程序中加载自定义 ConfigSection

asp.net-core - ASP.Net 核心 : asp-action tag not working