2013-09-26 30 views
0

我已阅读&了解a question,它描述了如何向函数添加参数。我想知道如何让更多的模块化代码和插件更加严格。我将如何去创建default参数值和用户options在您的插件或您的功能?在JavaScript或jQuery中创建用户可配置功能

$('.pluginAttachment').yourCoolPlugin({ 
    parameter1: false, //User added 
    //the rest of the options 
    //Still adds the rest of the default options except above 
}); 

我明白,这些都是变量,但我不知道如何将它们交织成整体功能为User参数,可以将采取遵于默认。

+0

找到我需要这里的信息:http://stackoverflow.com/questions/4200701/jquery-plugin-methods-how-can-i-pass-things-into-them?rq=1 – m33bo

回答

0

这是我如何做的一个例子。我喜欢做这种事情。使插件易于用户使用,并且易于增量增强。

(function ($) { 
$.fn.yourCoolPlugin = function(options) { 
     // Extend our default options with those provided. 
     // Note that the first arg to extend is an empty object - 
     // this is to keep from updating our "defaults" object. 
     var opts = $.extend({}, $.yourCoolPlugin.defaults, options); 

     // Now your opts variable wil have either the defaults or values passed by the user. 
     DoSomething(opts.parameter1, opts.parameter2); 
}; 

$.yourCoolPlugin.defaults = { 
    parameter1:false, 
    parameter2:"header"  
}; 
})(jQuery); 
相关问题