What causes jQuery “$(…) is null” on some pages?

2019-02-22 08:47发布

问题:

I have some javascript which controls a hidden div. Now it works on most pages, but on other pages with other javascripts it is not working... Is my js written poorly?

$(document).ready(function() {
$("#user-dropdown-toggle").live ('click', function() {
    $("#left-user-bar").addClass("open");
    $("#user-dropdown-toggle").addClass("league-judgement");
    $("body").addClass("league-judgement");
});
$(".league-judgement").live('click', function() {
  $("#left-user-bar").removeClass("open");
  $("#user-dropdown-toggle").removeClass("league-judgement");
  $("body").removeClass("league-judgement");
});
});

Firefox is reporting the following in the error console:

Timestamp: 4/18/2012 9:08:21 PM Error: $("#user-dropdown-toggle") is null

回答1:

The $ function in jQuery will never return null. So it is likely it is a different non-jQuery $ in use. (Is there any ASP.NET stuff or prototype.js or other library being used? A custom $ function declared later on?)

I know that $ is itself not null because the exception would be different, such as: "$ is not a function". In this case the browser is saying the result of the expression ($(...)) is null, which leads me to the above conclusion.

Try:

$(document).ready(function($) { // <-- note $ there
   ...
});

Or, better yet, as it only relies on window.jQuery and not window.$:

jQuery(function($) { // <-- note $ there
   ...
});

And, if that works, then it is that $ is being clobbered before the "ready" event (but after $(...).ready). Of course, it is possible (but not very likely) that the $ is already not jQuery at this point...

To see if $ is jQuery (use the Web Developer Console or Firebug):

  • $ === jQuery should generally be true, but it might not be depending on noConflict and such
  • $.fn.jquery and $().jquery should both result in the jQuery version as a string
  • $ (just specifying the function on the console will "display the source")

As an aside, I would indent the function body (e.g. in the "ready" callback) to see where it start/ends more clearly.

Happy coding.



回答2:

The first thing I would check is to make sure jQuery is included on all pages. I assume this is the case since it did not have issue with the $(document).ready bit but you never know.

Take a look at this post for more info: jQuery $("#field") is null?



回答3:

You should add your jquery script/include line.

Also you mention "other JS" on same page.. you should check that it is not loading a different version of JQuery than the one you are using -- overriding your imported version of your library.....