asp.net mvc4 jquery 不工作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12173799/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:23:11  来源:igfitidea点击:

asp.net mvc4 jquery not working

jqueryasp.net-mvcrazor

提问by davidcoder

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

我正在尝试运行放在我的_Layout.cshtml 中的 jquery 代码,如下所示:

...............
<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 workedif 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 代码放在外部文件中,但真的想澄清我做错的地方。

回答by NunoCarmo

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>

回答by user1462933

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.

安德烈亚斯,我有同样的问题..默认情况下,“_layout.cshtml”在文档末尾有“@Scripts.Render("~/bundles/jquery")”,但它不起作用..我剪了它并将其粘贴在头部,现在它正在工作。

回答by DanKodi

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. Then you have any scripts. That's what this means. So in your views do something like this.

首先你有 jQuery 库。然后你有任何脚本。这就是这个意思。所以在你看来,做这样的事情。

@section scripts{
 //your script
}

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

这将确保所有脚本都在 jQuery 参考之下。