asp.net mvc4 jquery not working

梦想的初衷 提交于 2019-12-14 03:39:57

问题


I'm trying to run a jquery code which was put in my _Layout.cshtml as below:

...............
<script type='text/javascript'>
$(document).ready(function () {
   alert('Test');

});
</script>
  @Scripts.Render("~/bundles/jquery")
  @RenderSection("Scripts", required: false) 
</body>
</html>

The above code wasn't fired and when I inspected with Chrome Dev, it showed $ is not defined ( I can see all my jquery, jquery ui files are loaded )

It worked if I put this code in an external js file

I don't mind putting all my jquery code in external files, but really wanna clarify where I am doing wrong.


回答1:


You need to introduce jquery before your script.

@Scripts.Render("~/bundles/jquery")

<script type='text/javascript'>
$(document).ready(function () {
   alert('Test');

});
</script>

  @RenderSection("Scripts", required: false) 
</body>
</html>



回答2:


Andreas, i have the same issue.. for default the "_layout.cshtml" has "@Scripts.Render("~/bundles/jquery")" at the end of the document, but it doesn't work.. i cut it and paste it in the head and now it is working.




回答3:


In order for jQuery to work, your script should come after <script src="/Scripts/jquery-2.0.3.js"></script>

In the _Layout.cshtml, just before the </body> tag you can find something like this

@Scripts.Render("~/bundles/jquery")
@RenderSection("scripts", required: false)

First you have the jQuery library. Then you have any scripts. That's what this means. So in your views do something like this.

@section scripts{
 //your script
}

This will make sure that all scripts comes under jQuery reference.



来源:https://stackoverflow.com/questions/12173799/asp-net-mvc4-jquery-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!