简体   繁体   中英

Dynamic Arrays for Jquery Plugins

I am building a simple JQuery plugin in which a user can build modules that contain a title, subtitle, and text.

I want to allow the user to be able to add multiple elements to the module in one plugin call.

var methods = {
    build : function( options ) {
    var settings = $.extend( {
        'header'    : 'Untitled',
        'subtitle' : 'Subtitle',
        'content' : 'Lorem ipsum dolor amet...',
        'img' : ''  //img URL
    }, options);

    //Create the div to hold elements
    var box = $('<div/>', {
        class: 'service'
    }).appendTo(this);

    //Populate div with header
        $('<h2/>', {
        class: 'service-title',
        text: settings.header
    }).appendTo(box);

    //Check for subtitle
    if(settings.subtitle != 'Subtitle') {
        $('<h4/>', {
            class: 'service-sub',
            text: settings.subtitle
        }).appendTo(box);
    }

    //Add body text
    $('<p/>', {
        class: 'service-text',
        text: settings.content
    }).appendTo(box);

    //Check for image
    if(settings.img != '') {
        $('<img/>', {
            class: 'service-img',
            src: settings.img
        }).appendTo(box);
    }


    },
    add : function() {

    }
};

          $.fn.service = function( method ) {
                if ( methods[method] ) {
                    return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1));
                } else if ( typeof method === 'object' || ! method ) {
                    return methods.build.apply( this, arguments );
                } else {
                    $.error( "Method " + method + " does not exist for the Servicer" );
                }
          };
        })( jQuery );

In the variable settings, under subtitle, I would like to allow users to add more than one subtitle within one call to .service()

Allow user to make subtitle option an array instead of string. Test if it is a string or array ,if it is an array run a loop.

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