简体   繁体   中英

jQuery .fn is saying “not a function”

When I call this custom function

$.fn.inputBoxHelper = function () {
    var args = arguments[0] || {};
    var matchingElem = $.grep(this, function (e) { return $(e).val() == $(e).attr('title'); });
    $(matchingElem).addClass(args.className);

    this.bind({
        focus: function(){
            if ($(this).val().trim() == $(this).attr('title')) { $(this).val(emptyString).removeClass('gray'); }
        },
        blur: function(){
            if ($(this).val().trim() == emptyString) { $(this).val($(this).attr('title')).addClass('gray'); }
        }
    });
    return this;
}

Like this

$('input:text').inputBoxHelper({ className: 'gray' });

It gives me the error when I call it

$("input:text,input:checkbox").inputBoxHelper is not a function
file:///D:/repository/scripts/script_tests/test.js
Line 20

Even when I change the function to just

$.fn.inputBoxHelper = function () {return this;}

it does the same thing. It seems to run fine and work correctly as all the functionality works on the input boxes but get the error. Anyone have any ideas?

Check that you're not loading jQuery into the page twice. Some plugins or plugin libraries like to include jQuery. So it can overwrite your existing jQuery instance and override the $ and jQuery variables with a new – fresh – instance causing existing plugins to be undefined. Plugins are added to the prototype of jQuery when they are defined. So if you destroy the only instance of that object, then the prototype is reset to its original form. And therefore those plugins are no longer part of that prototype.

Also, it may be nothing, JSLint is reporting that you're missing a semicolon on the last line of that function definition you posted. It ought to be:

$.fn.inputBoxHelper = function () {
  var args = arguments[0] || {};
  var matchingElem = $.grep(this, function (e) { return $(e).val() == $(e).attr('title'); });
  $(matchingElem).addClass(args.className);

  this.bind({
     focus: function(){
          if ($(this).val().trim() == $(this).attr('title')) { $(this).val(emptyString).removeClass('gray'); }
      },
      blur: function(){
          if ($(this).val().trim() == emptyString) { $(this).val($(this).attr('title')).addClass('gray'); }
      }
  });
  return this;
};

It's always a good idea to run all of your javascript through JSlint. It can help you find stuff that you might spend hours looking for otherwise.

The plugin needs to be loaded before it can be used.

Comments above confirm that OP was attempting to use the plugin before it was loaded.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM