2015-04-16 39 views
0

我有這樣一個(簡化代碼)佈局頁面局部視圖和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()指令保證嗎?

+0

而你確定jquery被加載....最終? – Mark

+0

我相信,如果我在jQuery加載後移動腳本,一切都可以正常工作。但我不想將它移出部分。 – Lorenzo

+1

$(document).ready()只會在JQ被加載時才起作用,因爲它本身是一個jquery函數......如果您使用了DOMContentLoaded事件,那該怎麼辦? document.addEventListener('DOMContentLoaded',function(){ // ... });代替? – Mark

回答

3

$(document).ready()如果JQ加載只會工作運行,因爲它本身是一個jQuery功能。

如果您使用DOMContentLoaded事件而不是?

document.addEventListener('DOMContentLoaded', function() { 
          // Your code 
}); 
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 
+0

感謝您的回答。我確實選擇了Mark Answer,因爲他提出了一個可行的解決方案 – Lorenzo

2

其實你正在加載jQuery之前的部分視圖。所以首先嚐試執行$(document)然後你會得到$未定義。試試這個

<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> 
+0

感謝您的回答。這也會起作用。我確實選擇了Mark Answer,因爲它不需要修改佈局。再次謝謝你。 – Lorenzo

+1

@Lorenzo這是一個令人失望的選擇,因爲Aravind的答案更清晰。你已經接受了一種解決方法作爲答案,並且人們最終可能會在沒有意識到的情況下使用這種方法。 – ediblecode

+0

@jumpingcode:對。這是一種解決方法。但是我已經提出了這個答案,並解釋了爲什麼在我的情況下這不會是好事。即使對於像這樣的簡單更改,我也沒有任何改變應用佈局的機會。我很抱歉阿拉維德,我仍然感謝答覆。但在我的情況下,這個建議並不適用。 – Lorenzo