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


当前回答

我有同样的问题,并解决了它使用

document.addEventListener('DOMContentLoaded', () => {
 // code here
});

其他回答

是否使用其他JavaScript库?如果是这样,你可能需要在兼容模式下使用jQuery:

http://docs.jquery.com/Using_jQuery_with_Other_Libraries

我也遇到了同样的问题,这是因为我对jQuery.js的引用不在标签中。一旦我把它换了,一切都开始运转了。

安东尼

如果jQuery插件调用在</body>旁边,并且你的脚本是在</body>之前加载的,你应该让你的代码在窗口后运行。Onload事件,像这样:

window.onload = function() {
  //YOUR JQUERY CODE
}

`

因此,您的代码将只在窗口加载后运行,此时所有资产都已加载。此时,将定义jQuery($)。

如果你使用它:

$(document).ready(function () {
  //YOUR JQUERY CODE
});

`

$现在还没有定义,因为它是在jQuery加载之前调用的,你的脚本在控制台的第一行就会失败。

我使用Url。知足而从不有问题。

<script src="<%= Url.Content ("~/Scripts/jquery-1.4.1.min.js") %>" type="text/javascript"></script>

首先,您需要确保加载了jQuery脚本。这可能来自CDN或本地网站。如果你在尝试使用jQuery之前不先加载这个,它会告诉你jQuery没有定义。

<script src="jquery.min.js"></script>

这可能是在HEAD或页脚,只是确保你加载它之前,你试图调用任何其他jQuery的东西。

然后,您需要使用以下两种解决方案之一

(function($){
// your standard jquery code goes here with $ prefix
// best used inside a page with inline code, 
// or outside the document ready, enter code here
 })(jQuery); 

or

jQuery(document).ready(function($){
// standard on load code goes here with $ prefix
// note: the $ is setup inside the anonymous function of the ready command
});

请注意,很多时候$(document).ready(function(){//code here});不会起作用。