Reputation: 119
I created a simple ASP .Net Core (version 2.2) Web Application (non-MVC) in Visual Studio 2017 Community (Version 15.9.6)
By default, jQuery (version 3.3.1) is included in the wwwroot/lib/jquery directory.
I am getting jQuery IntelliSense.
jQuery is referenced in the default /Pages/Shared_Layout.cshtml file correctly.
I added the following code to the default.csthml page:
<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>
This simple code does not work by default.
I do not understand why.
Console Error
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>
Upvotes: 6
Views: 5829
Reputation: 32069
First add @RenderSection("Scripts", required: false)
at the bottom of the body
of your Layout.cshtml
page.
Then your scripts inside @section Scripts
as follows:
@section Scripts{
<script type="text/javascript">
$(document).ready(function () {
$("p").click(function () {
$(this).hide();
});
});
</script>
}
Hope this will solve your problem!
Upvotes: 10
Reputation: 78272
Based on your comment we can see that jQuery has not actually loaded by the time this script element is run. Typically you need to load jQuery in the head
element to make sure it is available for script
elements defined in the body
.
Upvotes: 0