选项不适用于jQuery自定义插件

时间:2015-03-29 15:58:27

标签: jquery jquery-plugins

我只想创建自定义jQuery插件。我按照Tutplu的教程来创建它。我写了以下示例代码。但它没有将样式应用于h1元素。

 if(typeof Object.create !== 'function') {
        Object.create = function(obj) {
            function F() {};
            F.prototype = obj;
            return new F();
        };
    }

(function($, window, document, undefined) {

    var Modal = {
        init: function(options, el) {
            var self = this;
            self.elem = el;
            self.options = $.extend({}, $.fn.modal.options, options);
        }
    };

    $.fn.modal = function(options) {

        return this.each(function() {
            var myModal = Object.create(Modal);
            myModal.init(options, this);
        });

    };

    $.fn.modal.options = {
        color: '#556b2f',
        backgroundColor: 'red'
    };


})(jQuery, window, document);

$(document).ready(function() {
    $('h1').modal();
});

如何将选项应用于h1元素?

1 个答案:

答案 0 :(得分:1)

修改你的init()以循环选项并应用为css样式,如下所示:

var Modal = {
     init: function (options, el) {
         var self = this;
         self.elem = el;
         self.options = $.extend({}, $.fn.modal.options, options);
         for (var prop in self.options) {
             if (self.options.hasOwnProperty(prop)) {
                 $(self.elem).css(prop, self.options[prop]);
             }
         }
     }
 };
相关问题