如何将变量转换为选项

How to turn variables in to options?

本文关键字:选项 转换 变量      更新时间:2023-09-26

可能重复:
您将如何更改这种代码?

我该如何通过jQuery将这些变量传递给选项,这样当用户使用插件时,他们必须从HTML初始化插件,如下所示:

 <script>
    $('.elem').pluginName({
       theme: 'blue',
       animSpeed: 200
    });
 </script>

这是我的jQuery代码。很乱,但看看。如何将变量更改为选项?

$(function () {
    var theme = "sunburst";
    var btnColor = "yellow";
    var icon = "power";
    var message = "Hello World";
    var animSpeed = 300;
    var animType = 'fadeIn';
    var btnText = "Purchase";
    var btnLink = 'http://www.google.com';
    var closeStyle = "dark";
    var content =
        '<div id="mn_close" class="' + closeStyle + '"></div>' +
        '<div id="mn_border"></div>' +
        '<i class="icon-' + icon + '"></i>' +
        '<span class="mn_message">' + message + '</span>';
        //  '<a href="' + btnLink + '" class="button ' + btnColor + '">' + btnText + '</a>';

    $("#mn_close").live("click", function () {
        $('.mn_bar').animate({
            height: '0'
        }, animSpeed, function () {});
    });
    var mn_bar = $(".mn_bar");
    mn_bar.append(content);
    $(function () {
        mn_bar.addClass("animated");
        mn_bar.addClass(animType);
        mn_bar.addClass(theme)
    });
});

或者这是jsfiddle。http://jsfiddle.net/LwGRV/6/

我也一直在尝试将代码实现为这种标准类型的jQuery代码,但未能合并:

;(function ( $, window, document, undefined ) {
    var pluginName = "defaultPluginName",
        defaults = {
            propertyName: "value"
        };
    function Plugin( element, options ) {
        this.element = element;
        this.options = $.extend( {}, defaults, options );
        this._defaults = defaults;
        this._name = pluginName;
        this.init();
    }
    Plugin.prototype = {
        init: function() {
        },
        yourOtherFunction: function(el, options) {
            // some logic
        }
    };
    $.fn[pluginName] = function ( options ) {
        return this.each(function () {
            if (!$.data(this, "plugin_" + pluginName)) {
                $.data(this, "plugin_" + pluginName, new Plugin( this, options ));
            }
        });
    };
})( jQuery, window, document );

如果有人能对此有所了解,请提前表示感谢。

您应该了解以下内容:http://api.jquery.com/jQuery.extend/您的变量应该存储在一个对象中。