2013-09-26 31 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); 
相關問題