I'm trying to build a simple jquery plugin that can take selectors as parameters. All of the examples I find expect more raw 'properties' (width, color, etc) than actual selectors. Are there any good ways to do this?
I found this article : Passing jquery selector to sub-function within a plugin
But I'm still relatively confused.
The goal is 开发者_运维问答kind of like this ...
(function ($) {
$.fn.demonstration = function (options) {
var defaults = {
$selector: null
};
var options = $.extend(defaults, options);
return this.each(function () {
alert($selector.attr('id'));
});
};
})(jQuery);
$('body').demonstration({ $selector: $('#canvas') });
A selector is nothing more than a string. As long as you wrap any access to a jQuery() ($) call, people can pass in pretty much anything (a selector string, a jQuery object, a DOM element, etc.)
Edit: Saw you added code, in this case you should access it by $(options.$selector).attr('id')
.
Out of curiosity, why the $ before selector?
精彩评论