I am trying to write my first jQuery plugin. Following the jQuery plugin docs I did this:
(function($) {
$.fn.selection = function(array, n) { ... };
}(jQuery));
But when I try to run it with some code like this:
var array = [5, 2, 1, 5, 9];
alert($.selection(array, 2));
I get the error Uncaught TypeError: Object function (j,s){return new b.fn.init(j,s)} has no method 'selection'
.
However, when I loose the .fn
like this:
(function($) {
$.selection = function(array, n) { ... };
}(jQuery));
Everything works. Why doesn't the original example work by adding to the jQuery.fn
object like the jQuery doc 开发者_StackOverflowsuggests?
$.fn is the prototype used to jQuery objects created from $("...").
$ is the jQuery factory and namespace.
So
$.mymethod = function (){}
can only be called through
$.mymethod()
But
$.fn.mymethod = function () { this.remove(); }
can be called like this.
var divs = $(".mydivs");
divs.mymethod();
And in the second example the mymethod will be called using the jQuery selection as object and would remove all matching divs.
Read more here:
http://docs.jquery.com/Plugins/Authoring
When you use $.fn.selection
the function is only avalable for jquery objects i.e $("<SOME_SELECTOR>").selection
精彩评论