jQuery isn't loading and '$' is undefi

2019-03-30 03:59发布

I am trying to do a very basic thing with jQuery, and it's not working at all in IE8 but works fine in Firefox, Safari and Chrome; IE gives me an "Object Expected" all the time.

Can anyone help? I'm not sure what is wrong as the page is very basic:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
    <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.2.min.js"></script>
    <script type="text/javascript">
        $(function() { 
            alert("It works!");
        });
    </script>
</head>
<body>
</body>
</html>

IE (and only IE) gives me an error saying "Object Expected" on the loading code. I have the IE Dev Toolbar and $ is undefined but in Firebug it comes up as "function". really don't know what is causing this.

6条回答
祖国的老花朵
2楼-- · 2019-03-30 04:28

This works perfectly well in my copy of Internet Explorer 8.0.7600.16385 on Windows 7.

Something must be up with your browser configuration.

查看更多
时光不老,我们不散
3楼-- · 2019-03-30 04:33

Well, I feel like an idiot. I don't know how (I certainly didn't change it!) but somehow my IE was disabling JavaScript, so no wonder it was not working! I only use FireFox when I can help it.

查看更多
Lonely孤独者°
4楼-- · 2019-03-30 04:36

You probably need to put your function in the ready eventhandler like so:

$(document).ready(function () {
   $(function() {
     alert("It works!");
   }):
});

That way the entire dom has been processed before your function gets run.

查看更多
迷人小祖宗
5楼-- · 2019-03-30 04:41

I've ran into this issue before. It can be caused by a number of things, but the simplest solution I've found is using "jQuery" in place of a dollar sign.

jQuery(function() { 
            alert("It works!");
});
查看更多
该账号已被封号
6楼-- · 2019-03-30 04:42

I use the HTML5Boilerplate method of:

<!-- Grab Google CDN's jQuery, with a protocol relative URL; fall back to local if necessary -->
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.js"></script>
  <script>window.jQuery || document.write("<script src='js/libs/jquery-1.5.1.min.js'>\x3C/script>")</script>

EDIT:

Btw ... I use this from IE6-IE9, Firefox, Chrome, Safari, and Opera and I don't ever have an issue with $ being undefined. If you have plugins, I would use this pattern to ensure variables are what they should be:

(function($, window, document, undefined) {

    // code here

})(jQuery, this, document);
查看更多
Animai°情兽
7楼-- · 2019-03-30 04:45

you could try alternative syntax for initiating like this:

(function($){
    $(function(){

    })
})(jQuery)
查看更多
登录 后发表回答