我有一个简单的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应用程序,我确信我真的很密集,谷歌上的所有地方都说要检查文件是否被正确引用,我已经检查了一遍又一遍,请建议!: /


当前回答

这个错误意味着jQuery还没有加载到页面上。使用$(document).ready(…)或其任何变体都没有好处,因为$是jQuery函数。

使用窗口。Onload应该在这里工作。注意,只有一个函数可以分配给window.onload。为了避免丢失原始的onload逻辑,你可以像这样装饰原始函数:

originalOnload = window.onload;
window.onload = function() {
  if (originalOnload) {
    originalOnload();
  }
  // YOUR JQUERY
};

这将执行最初分配给window的函数。onload,然后执行// YOUR JQUERY。

有关装饰器模式的更多详细信息,请参阅https://en.wikipedia.org/wiki/Decorator_pattern。

其他回答

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库还没有加载。

您可以在拖动jQuery库后移动代码。

或者你可以用这样的东西

window.onload = function(){
  // Your code here
  // $(".some-class").html("some html");
};  

如上所述,它的发生是由于$变量的冲突。

我通过为jQuery保留一个没有冲突的次要变量来解决这个问题。

var $j = jQuery.noConflict();

然后在任何地方使用它

$j( "div" ).hide();

更多细节可以在这里找到

在我的情况下,我指向谷歌托管JQuery。它被正确地包含在内,但我在一个HTTPS页面上,并通过HTTP调用它。一旦我修复了这个问题(或允许不安全的内容),它就立即启动了。

这是解决这个问题的常见问题,你必须检查一些点

包含主要Jquery库 检查跨浏览器问题 添加库顶部的jquery代码 检查cdn可能被阻止。

详情请见本博客