TypeError: $(…) is null error in firebug but code works on jsFiddle

假如想象 提交于 2019-11-29 15:51:51
  1. Make sure jQuery is loaded before you run your custom script
  2. Did you copy your code from JSFiddle and then used it immediately? Fiddle code has the habit to be corrupt. The ; is often defined as an invalid character. Remove it and retype it yourself.

ADDED: 3. As John Fontaine pointed out, it is possible that jQuery conflicts with another library. To bypass this, you canuse jQuery noConflict mode. The documentation is quite clear on this, but I'll give some examples, just in case.

The best methods are the following, or at least that is my preference:

Use another variable instead of $, such as $j. By doing so, it is clear to you and to any other revisor of your code that this code depends on another library than $.

Example:

var $j = jQuery.noConflict();

// Use jQuery via $j(...)
$j(document).ready(function () {
  var secondary = $j("#secondary-footer");
  secondary.hide().addClass("fixed").fadeIn("fast");

  $j(window).scroll(function () {
    if (secondary.offset().top >= ($j(document).height() - 350)) {
      secondary.removeClass("fixed");
    } else if (secondary + ":not('.fixed')") {
      secondary.addClass("fixed");
    }
  });
});

The "danger" of this method is that you might forget to use this variable sometimes. What you can do is start of by using the normal dollar sign and when you have finished, do a find of replace.

Possibly the most straight-forward method:

jQuery(function ($) {
  var secondary = $("#secondary-footer");
  secondary.hide().addClass("fixed").fadeIn("fast");

  $(window).scroll(function () {
    if (secondary.offset().top >= ($(document).height() - 350)) {
      secondary.removeClass("fixed");
    } else if (secondary + ":not('.fixed')") {
      secondary.addClass("fixed");
    }
  });
});

This allows you to use jQuery in that block, i.e. the block that starts with jQuery(function ($) { and ends with });.

Blackboard Learn uses the prototypejs http://www.prototypejs.org/ library on most pages. If you want to use JQuery scripts and plugins you must use no-conflict mode and invoke your $('') style calls as JQuery('') calls instead. See JQuery docs at http://docs.jquery.com/Using_jQuery_with_Other_Libraries

I have several scripts running on same page using jQuery.noConflict();

var $j = jQuery.noConflict();

function getTheme() {
    var theme_id = $j(".current").attr("id"); // error occurs this line
    var theme = $j("#"+theme_id).find("a").html();
    return theme.toUpperCase();
}

just use $j where $ or you can use create more by using jQuery.noConflict()

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!