我有一个像这样的布局页面(简化代码)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>@Resources.LayoutPageTitle | @ViewBag.Title</title>
[...other code omitted...]
</head>
<body id="page-top">
@Html.Partial( "_LandingNavbar" )
[...other code omitted...]
<!-- Placed at the end of the document so the pages load faster -->
<!-- jQuery -->
<script src="~/assets/js/jquery/jquery-2.1.3.min.js"></script>
@RenderSection( "scripts", required: false )
</body>
</html>
正如您所看到的,我在加载jQuery脚本之前加载了一个部分视图。在我的部分视图中,代码类似于以下
<div class="dropdown profile-element">
<span class="text-center" id="userInfo"></span>
</div>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
url: '/GetUserInfo',
data: {},
dataType: 'json',
success: function (data) {
alert(data);
}
});
});
</script>
但我得到
ReferenceError:$未定义
https://localhost:44301/ 第237行
据说jQuery脚本执行时仍未加载jQuery。但这不应该由$(document).ready(function ()
指令保证吗?
答案 0 :(得分:3)
$(document).ready()
只有在加载JQ时才有效,因为它本身就是一个Jquery函数。
如果您使用DOMContentLoaded事件,该怎么办?
document.addEventListener('DOMContentLoaded', function() {
// Your code
});
答案 1 :(得分:3)
实际上你是在jquery之前加载局部视图。所以首先它尝试执行$(文档),然后你将得到$未定义。试试这个
<head>
//[...other code omitted...]
<!-- jQuery -->
<script src="~/assets/js/jquery/jquery-2.1.3.min.js"></script>
</head>
<body id="page-top">
@Html.Partial( "_LandingNavbar" )
[...other code omitted...]
<!-- Placed at the end of the document so the pages load faster -->
@RenderSection( "scripts", required: false )
</body>
答案 2 :(得分:0)
尝试将函数连接到导致错误的$(document).ready事件是一种行为。即使您不打算在页面加载之前执行该函数,jQuery构造函数仍然在jQuery导入之前运行
$(document).ready(function(){}) // use jquery to find the document object, then wire up this function to the ready event
<script src="~/assets/js/jquery/jquery-2.1.3.min.js"></script> // go ahead and import jquery