你会如何改变这种代码?

我有以下代码,但我仍然是jQuery的新手,我很确定这是一个混乱的代码,可以缩短或可能使用更少的变量来创建一个更好的动态插件。 我正在尝试不同类型的逻辑。 这是代码。

$.pluginName = (function () { $(function () { var message = "Hello World!"; var animSpeed = 300; var animType = 'fadeIn'; var icon = "pin"; var btnText = "Purchase"; var btnColor = "pink"; var btnLink = 'http://www.google.com'; var content = '
' + '
' + '' + '' + message + '' + '' + btnText + ''; $("#mn_close").live("click", function () { $('.mn_bar').animate({ top: '-50' }, animSpeed, function () {}); }); $(".mn_bar").append(content); $(function () { $(".mn_bar").addClass("animated"); $(".mn_bar").addClass(animType); }) }) })(jQuery);

有关如何将这些变量传递给用户可以从HTML源动态更改的选项的任何提示? 我不期待详细的答案,但我很感激任何帮助传递。

EDI:JS小提琴CSS和HTML。

http://jsfiddle.net/QjFnf/8/

提前致谢!

看看这是否有帮助:

 (function( $ ){ var _defaults = { message = 'Hello World!', animSpeed = 300, animType = 'fadeIn', icon = 'pin', btnText = 'Purchase', btnColor = 'pink', btnLink = 'http://www.google.com' }; $.pluginName = function( opts ) { var o = $.extend( {}, _defaults, opts ) , $bar = $('.mn_bar').addClass('animated '+ animType) , $close = $('
') , $icon = $('') , $message = $(''+ o.message +'') , $link = $(''+ o.btnText +''); $close.click(function(){ $bar.animate({ top: '-50px' }, animSpeed ); }); $bar.append( $bar, $close, $icon, $message, $link ); }; })( jQuery );

基于@kennypu评论,我已经这样做了:我根本没有测试它,但我认为这是重构插件的好方法:

 (function( $ ) { $.fn.myPlugin = function( options ) { // Create some defaults, extending them with any options that were provided var settings = $.extend( { message : "Hello World!", animSpeed : 300, animType : 'fadeIn', icon : "pin", btnText : "Purchase", btnColor : "pink", btnLink : 'www.google.com', }, options); // A tidier way to create the content would be to use jQuery like this : http://api.jquery.com/jQuery/#jQuery2 var content : '
' + '
' + '' + '' + settings.message + '' + '' + settings.btnText + ''; var mn_bar = $(".mn_bar"); mn_bar.append(content); $("#mn_close").on("click", function () { mn_bar.animate({ top: '-50' }, settings.animSpeed, function () {}); }); mn_bar.addClass("animated " + settings.animType); }) })(jQuery);

编辑:我为.mn_bar设置了一个变量,因为没有理由再次在DOM中查找这个元素。 我还删除了对addClass()的两个调用,并且只调用了一个。