Ciel
Ciel

Reputation: 17752

jQuery, passing selectors as option parameters

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') });

Upvotes: 1

Views: 5923

Answers (1)

Matti Virkkunen
Matti Virkkunen

Reputation: 65126

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?

Upvotes: 4

Related Questions