我有一个简单的jquery点击事件

<script type="text/javascript">
    $(function() {
        $('#post').click(function() {
            alert("test"); 
        });
    });
</script>

以及在site.master中定义的jquery引用

<script src="<%=ResolveUrl("~/Scripts/jquery-1.3.2.js")%>" type="text/javascript"></script>

我已经检查了脚本被正确解析,我能够看到标记,并直接在firebug中查看脚本,所以我必须被发现。然而,我仍然得到:

$没有定义

jquery没有一个是有效的。我还尝试了它的各种变体,比如$(document)。ready和jQuery等。

这是一个。net 3.5上的MVC 2应用程序,我确信我真的很密集,谷歌上的所有地方都说要检查文件是否被正确引用,我已经检查了一遍又一遍,请建议!: /


当前回答

我也有同样的问题,但不知道是什么原因导致的。我最近将HTML文件从日语转换为UTF-8,但我没有对脚本文件做任何处理。不知何故,jquery-1.10.2.min.js在这个过程中被损坏了(我仍然不知道是怎么回事)。用原来的替换jquery-1.10.2.min.js修复了它。

其他回答

有一种方法可以让它在其余代码运行之前自动加载javascript。

进入Views\Shared_Layout.html并添加以下内容

<head>
  <*@ Omitted code*@>
  <script src="~/Scripts/jquery-1.10.2.min.js" type="text/javascript"></script>
</head>

我只是做了同样的事情,发现我有很多

type="text/javacsript"

所以他们正在加载,但没有进一步提示为什么它不能工作。不用说,正确的拼写解决了这个问题。

I had this problem once for no apparent reason. It was happenning locally whilst I was running through the aspnet development server. It had been working and I reverted everything to a state where it had previously been working and still it didn't work. I looked in the chrome debugger and the jquery-1.7.1.min.js had loaded without any problems. It was all very confusing. I still don't know what the problem was but closing the browser, closing the development server and then trying again sorted it out.

如果你把你的jquery.js文件放在html文件所在的同一个文件夹下,或者在一些子文件夹中,Firebug的问题就解决了。例如,如果你的html文件在C:/folder1/下,那么你的js文件应该在C:/folder1/(或C:/folder1/folder2等)下的某个地方,并在html文档中相应地定位。希望这能有所帮助。

当在asp.net中使用jQuery时,如果你正在使用一个母版页,并且你正在加载jQuery源文件,请确保在所有jQuery脚本引用之后有头部内容占位符。

我有一个问题,任何使用该母版页的页面都会返回“$ is not defined”,仅仅是因为错误的顺序使客户端代码在jquery对象创建之前运行。所以确保你有:

<head runat="server">
    <script type="text/javascript" src="Scripts/jquery-VERSION#.js"></script>
    <asp:ContentPlaceHolder id="Header" runat="server"></asp:ContentPlaceHolder>
</head>

这样代码将按顺序运行,并且您将能够在子页面上运行jQuery代码。