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 badges4 Answers
Reset to default 6Actually 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
评论列表(0条)