开发者

Plugin doesn't work when I use .fn, but does if I leave it off

开发者 https://www.devze.com 2023-02-07 09:49 出处:网络
I am trying to write my first jQuery plugin.Following the jQuery plugin docs I did this: (function($) {

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

0

精彩评论

暂无评论...
验证码 换一张
取 消