简体   繁体   中英

How to use options when writing a jQuery plugin?

Here's my code ( http://jsfiddle.net/nB4Hg/ ):

JQuery:

// plugin code
(function($) {
    $.fn.coloredDiv = function(options) {

            // defaults
            var options = {
                 'color' : 'black'
            };

            $(this).css('background', options.color);

    }
})(jQuery);


        // use the plugin
        $(function() {

            $("#foo").coloredDiv({ 'color' : 'red' });
            $("#bar").coloredDiv();

        });

CSS:

    div { width: 100px; height: 100px; margin-bottom: 10px; }

HTML:

<div id="foo"></div>
<div id="bar"></div>

Now I am trying to learn how to use options when writing plugins. In my code what I'm trying to do is specify that the first div should be colored red and the second since it has no options should be the default black. However both are black. What am I doing wrong?

Your current approach is accepting a parameter named options , but then declaring another variable named options that "shadows" the parameter, and thus the passed-in options never get seen by the subsequent code.

Instead, you should declare your default options, then use $.extend to overwrite those defaults with the ones passed in by the user, where applicable:

$.fn.coloredDiv = function (userOptions) {
    var options = $.extend({
        color: "black"
    }, userOptions);

    // ...
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM