简体   繁体   English

asp.net mvc4 jquery无法正常工作

[英]asp.net mvc4 jquery not working

I'm trying to run a jquery code which was put in my _Layout.cshtml as below: 我正在尝试运行一个jQuery代码,它放在我的_Layout.cshtml中 ,如下所示:

...............
<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 ) 上面的代码没有触发,当我用Chrome Dev检查时,它显示$没有定义 (我可以看到我所有的jquery,jquery ui文件都已加载)

It worked if I put this code in an external js file 它的工作 ,如果我在一个外部JS文件把这个代码

I don't mind putting all my jquery code in external files, but really wanna clarify where I am doing wrong. 我不介意将我所有的jquery代码放在外部文件中,但确实想弄清楚我在哪里做错了。

You need to introduce jquery before your script. 您需要在脚本之前引入jquery。

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

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

});
</script>

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

安德里亚斯,我有同样的问题..默认情况下,“ _ layout.cshtml”在文档末尾有“ @ Scripts.Render(“〜/ bundles / jquery”)“”,但它不起作用。并将其粘贴到头部,现在可以使用了。

In order for jQuery to work, your script should come after <script src="/Scripts/jquery-2.0.3.js"></script> 为了使jQuery正常运行,您的脚本应<script src="/Scripts/jquery-2.0.3.js"></script>

In the _Layout.cshtml, just before the </body> tag you can find something like this 在_Layout.cshtml,就在之前</body>标签,你可以找到这样的事情

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

First you have the jQuery library. 首先,您拥有jQuery库。 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. 这样可以确保所有脚本都属于jQuery参考。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM