$ is not defined error

"$" 是在jquery里面定义的。

在一次项目中遇见这个错误:“$ is not defined error”.找了半天,网上都说是$没有定义,或者是js没有引入,但是我确实导入了。后来看到一片文章,才发现是js引入的时候顺序错了,给Jquery放在了后面引入,但是我前面已经用到jquery了。

如果页面出现问题,我推荐使用“Firefox” 的 debug来调试。举个例子:

我出现这个问题,也同样引入了jquery,而且位置对,还是提示这个问题。所以我就用 Firefox 的debug来看看js到底有没有加载到,看过之后才发现jquery加载来,但是是从缓存里面读取的,所以我就将缓存清理了,再访问,ok

以下是我看到的文章:

 

此文出自:http://themaingate.net/dev/jquery/is-not-defined-error

$ is not defined error
Posted Apr 5th, 2009 by David Calhoun in jquery

I first ran into this error when I started using jQuery.  It turns out it’s a somewhat common (beginner’s) mistake of trying to run a script without first waiting for jQuery to finish loading, which results in a race condition.  The easiest fix for this is to make sure jQuery has its own separate script tag right above your own jQuery-dependent script:

view sourceprint?
1.
2.

This will ensure that myscript.js is loaded only after jQuery is loaded.  Of course there are other ways to do this, notably John Resig’s degrading script pattern, but the above solution will at least solve the “$ is not defined” error, which is priority.

However, this may not be enough.  Theoretically it’s possible that jQuery doesn’t get loaded (due to some network error) but your script does.  In that case we come full circle to our original “$ is not defined” problem.  So how do we prevent this?

The first thing I thought of was to make sure $ is defined by wrapping it in an if-then statement.  Note that this does NOT fix the problem:

view sourceprint?
1.//note: this method DOES NOT work!
2.if ($) {    //check if $ is defined - but this check results in an error!
3.    $("#myselector").click (function () {});    //my jQuery code here
4.}

With the above code, we run into the same problem!  Arg!  But don’t despair.  It turns out we need to prevent this sort of error by using the good old try-catch block:

view sourceprint?
1.try {
2.    $("#myselector").click (function () {});    //my jQuery code here
3.} catch (e) {
4.    console.log (e.message);    //this executes if jQuery isn't loaded
5.}

And it works!  If $ is undefined (and therefore jQuery isn’t loaded), the error is caught and handled instead of exploding.

Since we don’t live in a perfect world, it would be a good idea to assume that jQuery will not always be loaded and that this “network error” scenario may well occur, so it would be good practice to run a check like this before executing code that depends on jQuery (and likewise for other scripts with other dependencies!).


转载请标明出处:龙企阁 http://blog.csdn.net/longxia1987

你可能感兴趣的:(javaScript)