开发者

jQuery, passing selectors as option parameters

开发者 https://www.devze.com 2022-12-25 03:36 出处:网络
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 go

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?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号