我有這樣一個(簡化代碼)佈局頁面局部視圖和jQuery
<!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: $ is not defined
https://localhost:44301/ Line 237
據說jQuery的還是當jQuery腳本執行尚未加載。但是這不應該由$(document).ready(function()
指令保證嗎?
而你確定jquery被加載....最終? – Mark
我相信,如果我在jQuery加載後移動腳本,一切都可以正常工作。但我不想將它移出部分。 – Lorenzo
$(document).ready()只會在JQ被加載時才起作用,因爲它本身是一個jquery函數......如果您使用了DOMContentLoaded事件,那該怎麼辦? document.addEventListener('DOMContentLoaded',function(){ // ... });代替? – Mark