这个简单的jquery插件示例有什么问题?

时间:2012-03-21 22:02:25

标签: jquery jquery-plugins

我做错了什么?它在我按照jquery文档中的建议分离方法之前有效。 致电:$(this).Slick('show');

(function ($) {

var methods = {

    // object literals for methods
    init: function (options) {

        // initialize settings
        var settings = $.extend({
            'location': 'center',
            'speed': 'normal'
        }, options);
    },
    show: function () {

        return this.each(function () {

            // plugin code here
            alert('success!');
        });
    },
    hide: function () {

        // hide
    }
};

$.fn.Slick = function (method) {
    // method calling logic -- jquery recommended / standard
    if (methods[method]) {
        return methods[method].apply(this, Array.prototype.slice.call(arguments 1));
    } else if (typeof(method === 'object' || !method) {
        return methods.init.apply(this, arguments);
    } else {
        $.error('Method ' + method + ' does not exist on jQuery.Slick');
    }
};
})(jQuery);

2 个答案:

答案 0 :(得分:3)

有两种语法错误。

缺少逗号:

return methods[method].apply(this, Array.prototype.slice.call(arguments 1));

缺少右括号:

} else if (typeof(method === 'object' || !method) {

答案 1 :(得分:1)

你可能觉得有用的其他东西。很长一段时间我都很难写jQuery插件,直到我最终创建了这个简单的公式,自从我开始使用它以来一直对我有用。

(function($) {
    if (!$.myExample) {
        $.extend({
            myExample: function(elm, command, args) {
                return elm.each(function(index){
                    // do work to each element as its passed through
                });
            }
        });
        $.fn.extend({
            myExample: function(command) {
                return $.myExample($(this), command, Array.prototype.slice.call(arguments, 1));
            }
        });
    }
})(jQuery);

这为您提供了开始设置jQuery插件所需的一切,该插件将通过$.myExample($("someEle"))$("someEle").myExample()

以典型的jQuery方式工作
相关问题