javascript - jQuery plugin to work without element - Stack Overflow

How does one make a jQuery plugin that is possible to execute without using an element selector?Like, u

How does one make a jQuery plugin that is possible to execute without using an element selector?

Like, usually it's:
$('#myElementID').myPluginFunction(myVariables);
But, instead:
$.myPluginFunction(myVariables);

Thanks in advance!

How does one make a jQuery plugin that is possible to execute without using an element selector?

Like, usually it's:
$('#myElementID').myPluginFunction(myVariables);
But, instead:
$.myPluginFunction(myVariables);

Thanks in advance!

Share Improve this question asked Feb 24, 2012 at 14:39 tomsseisumstomsseisums 13.4k20 gold badges88 silver badges148 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 6

Actually you just use $.extend() instead of $.fn.extend(), read here for more

$.fn.extend({
   myMethod: function(){...}
});
//jQuery("div").myMethod();

$.extend({
 myMethod2: function(){...}
});
//jQuery.myMethod();

You can do it like this:

$.myPluginFunction = function(vars) {
    //...
};

Use $.extend. Here's a small example:

$(function() {
    return $.extend({
      addDebugBorder: function(selection, size) {
        return selection.each(function() {
          var color, randomColor;
          randomColor = function() {
            return Math.floor(Math.random() * 256);
          };
          if (!size) size = '5px';
          color = 'rgb(' + randomColor() + ',' + randomColor() + ', ' + randomColor() + ')';
          return $(this).css('border', size + ' solid ' + color);
        });
      }
    });
  });

Then called like

$.addDebugBorder($("table tr td"), '1px');

edit- This example code should really have been a normal plugin, I think I modified it to take the selector rather then just working on div's only is why its a little weird.

Instead of assigning the plugin to the jQuery.fn object, just assign it to the root jQuery object itself.

jQuery.myPluginFunction = function(myVariables) {
   // plugin code
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745329736a4622822.html

相关推荐

  • javascript - jQuery plugin to work without element - Stack Overflow

    How does one make a jQuery plugin that is possible to execute without using an element selector?Like, u

    3小时前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信