jquery plugin syntax
I am trying to create a jquery plugin, and I want have the following options:
$.plugin_name(variable)
$(selector).plugin_name(variable)
The first case the plugin would not need to be applied开发者_开发知识库 to an element ( it could create one for example) the second case the same plugin will do whatever it does on the element/s selected
My question is: How do I specify inside the plugin this:
if (selector is not given) {
create an element
} else {
( for example) insert variable in elements matching the selector
}
You can use jQuery.fn.myPluginName = function()....
for plugins that operate on jQuery objects.
For a standalone function in the jQuery
namespace, you can just set jQuery.func_name = function()...
.
An example:
jQuery.fn.erase = function() {
return this.each(function() {
jQuery(this).remove();
});
};
jQuery("body").erase();
jQuery.erase = function(element) {
jQuery(element).erase();
};
jQuery.erase("body"); // exact same result.
By using $.myFunc
you are simply adding a function to the jQuery namespace.
By using $.fn.myFunc
, you are extending the jQuery prototype, which means that the this keyword inside the function will represent the jQuery object returned from the selector.
If you'd like them both to do the same thing, you can check for the jQuery instance and create a new element:
try this:
$.myFunc = $.fn.myFunc = function(first, second) {
if (!(this instanceof $)) {
return $.fn.myFunc.apply($('<div>'), arguments);
}
// begin plugin code here:
return this.each(function() {
$(this).text(first + ' ' + second);
});
};
// now you can call myFunc in two ways:
$('<div>').myFunc('foo','bar').appendTo('body')
$.myFunc('bar','foo').appendTo('body');
To cover $.plugin_name()
use:
jQuery.plugin_name = function(data) {
// do stuff
}
For $(selector).plugin_name()
use:
jQuery.fn.plugin_name = function() {
return this.each(function() {
// do stuff
});
};
See Plugins/Authoring.
精彩评论